在一个包含对象的数组中,检查某个键是否存在于任何一个对象中。

6
我有一个对象数组,需要查看其中是否存在某个键。这是我现在正在做的事情:
const arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
arr.map(o => o.foo && true).includes(true)
// true

有没有更好/更被接受的方法来完成这个任务?

5个回答

5
你可以使用 Array#some

var arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
result = arr.some(o => 'foo' in o)
console.log(result)

every()some()的区别

  • every():

它会检查所有对象上是否存在给定的键,并在不是所有对象都具有此键时返回false。

  • some():

它将检查是否至少有一个对象具有该键,如果有,则立即返回true。


4
const arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
var result = arr.some((value, index) => {
    return value.hasOwnProperty('bar')
});
console.log(result);

3

我会使用Array.prototype.some()函数:

const arr = [
  { id: 1, foo: 'bar' },
  { id: 2 }
];

var result = arr.some(e => e.hasOwnProperty('foo'));
console.log("The array contains an object with a 'foo' property: " + result);

var result = arr.some(e => e.hasOwnProperty('baz'));
console.log("The array contains an object with a 'baz' property: " + result);


1
如果搜索的属性值为假值(例如 foo: 0),则此方法将无法正常工作。 - Bartek Fryzowicz
@bartekfr 在我的使用情况中这不是问题(它总是一个大于0的整数),但感谢你指出来。 - nshoes
已更新答案。最初看起来像是 OP 寻找“真实”的属性值,而不是寻找该属性是否存在。 - Scott Marcus

1
如果你只想要一个true/false来确定元素是否存在,可以使用'some'。它会返回true/false。
const arr = [{ id: 1, foo: 'bar' }, { id: 2 }];
var key = 'foo';
var isInArray= arr.some(function(val, i) {
    return val[i][key];
});

0
你可以使用 Array#some

var arr = [{ id: 1, foo: 'bar' }, { id: 2 }],
    result = arr.some(o => 'foo' in o);

console.log(result);


1
这里应该使用some而不是这个吧? - Scott Sauyet

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