如何检查对象数组中是否存在某个键?

11
我试图查找对象数组中是否存在指定的键。如果该键存在,则返回true,否则返回false。我从文本框中输入键,然后检查该键是否存在于对象数组中,但是我无法做到这一点。
以下是我尝试过的代码:
var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}]

var val = $("input[name='type_ahead_input']").val();

if (obj[val]) {
    console.log('exists');
} else {
    console.log('does not exist');
}
如果我将输入设置为在对象数组中存在的 'the carribean',即使如此,它仍会在控制台中输出不存在。
我该如何解决这个问题?

1
可能是 在 JavaScript 对象中检查键是否存在? 的重复,并且 if (val in obj[0]) { - Slai
9个回答

13
您可以筛选对象数组并仅返回具有所需键的对象。然后,如果结果数组的长度大于零,则意味着存在具有该键的元素。
var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}];

var val = "the carribean";

var exists = obj.filter(function (o) {
  return o.hasOwnProperty(val);
}).length > 0;

if (exists) {
    console.log('exists');
} else {
    console.log('does not exist');
}

如果数组中包含具有所需键的对象,无论其值是undefined还是null,此函数都将返回true


6

您可以使用 typeof 检查 key 是否存在

if (typeof obj[0][val] !== "undefined" ) {
    console.log('exists');
} else {
    console.log('does not exist');
}

注意:因为您正在检查的对象是数组obj的元素0,所以存在索引0
这是一个演示:

var obj = [{
  "7364234":"hsjd",
  "tom and jerry":"dsjdas",
  "mickey mouse":"kfjskdsad",
  "popeye the sailor man":"alkdsajd",
  "the carribean":"kasjdsjad"
 }];

 if ( typeof obj[0]["the carribean"] !== 'undefined' ) {
  console.log('exists');
 } else {
  console.log('does not exist');
 }

如Cristy在下面所建议的那样,您也可以使用 obj[0][val] === undefined 您还可以:
var obj = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}];

var val = "7364234";

if ( val in obj[0] ) {
    console.log('exists');
} else {
    console.log('does not exist');
}

2
obj[0][val] === undefined 更易于阅读、编写和理解。同时请注意,即使值为undefined,键也可能存在。应使用 in 运算符:val in obj[0] - XCS
如果数组中存在多个对象,则此解决方案将失败。 - Praneeth Karnena

5
我建议使用Array.some()来判断一个键是否存在,以及使用Array.find()来获取找到的键的值,结合一些最近的语法。

let arr = [{"foo": 1}, {"bar":2}];

function isKeyInArray(array, key) { 
  return array.some(obj => obj.hasOwnProperty(key)); 
}

function getValueFromKeyInArray(array, key) { 
  return array.find(obj => obj[key])?.[key]; 
}

console.log(isKeyInArray(arr, "foo"), isKeyInArray(arr, "bar"), isKeyInArray(arr, "baz"));
console.log(getValueFromKeyInArray(arr, "foo"), getValueFromKeyInArray(arr, "bar"), getValueFromKeyInArray(arr, "baz"));


1
这是因为你有一个对象数组[{...},{...}]而不仅仅是一个对象{...}。要么使用一个对象并保留你的测试,要么使用Array.find方法搜索具有val属性的对象是否存在于你的数组中。例如:
var objArr = [{
    "7364234":"hsjd",
    "tom and jerry":"dsjdas",
    "mickey mouse":"kfjskdsad",
    "popeye the sailor man":"alkdsajd",
    "the carribean":"kasjdsjad"
}]

let val = $("input[name='type_ahead_input']").val();

var existingObj = objArr.find(function(element) {
  return typeof element[val] !== 'undefined';
});

if (existingObj[val]) {
console.log('was found');
} else {
console.log('not-found');

请查看: https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Array/find


1
你的obj是一个数组,所以要检测该键是否存在于数组中的任何对象中,需要遍历数组,然后查看每个对象的键。

var objArr = [{
  "7364234": "hsjd",
  "tom and jerry": "dsjdas",
  "mickey mouse": "kfjskdsad",
  "popeye the sailor man": "alkdsajd",
  "the carribean": "kasjdsjad"
}]

const contains = (string) =>
  objArr.findIndex(
    // Is the string contained in the object keys?
    obj => Object.keys(obj).includes(string)
  ) !== -1

console.log(contains('the carribean'))
console.log(contains('spaghetti'))


0
    Boolean(array.find(el => el.searchKey) // true or false

检查对象数组中是否存在键的简单方法。


0

@E. Sundin的回答我认为是最简单的。对于我的情况,我是这样做的...

let o = { 
    id: 2, 
    name: "jack", 
    age: 54, temp: 2323
}

if(!Object.keys(o).includes('id')) throw new BadRequest("Id was missing!");

如果您有一个通过循环创建的对象数组。
if(!o.every(elm => Object.keys(o).includes('id')) throw new BadRequest("Id was missing!");

希望它能够运行。

0

你需要从数组中获取对象 obj[0][val]

var validate = function() {
  var obj = [{
    "7364234": "hsjd",
    "tom and jerry": "dsjdas",
    "mickey mouse": "kfjskdsad",
    "popeye the sailor man": "alkdsajd",
    "the carribean": "kasjdsjad"
  }];

  var val = $("input[name='type_ahead_input']").val();
  console.log(val);
  if (obj[0][val]) {
    console.log('exists');
  } else {
    console.log('does not exist');
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input name="type_ahead_input" value="" onkeyup="validate()">


0

给你:

const array = [{ name:'Stark' }, { email:'stark@gmail.com' }, { roll: '14' }]

const result = array.some(item => item.hasOwnProperty('email'))

console.log('Does Email Exist: ', result);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接