问题
I have an array of objects, and need to see if a key exists in any of them. Here is what I am doing now:
const arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
arr.map(o => o.foo && true).includes(true)
// true
Is there any better/more accepted way to do this?
回答1:
I'd use the Array.prototype.some() function:
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);
回答2:
const arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
var result = arr.some((value, index) => {
return value.hasOwnProperty('bar')
});
console.log(result);
回答3:
You can use Array#some
var arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
result = arr.some(o => 'foo' in o)
console.log(result)
Difference between every() and some()
- every:
It will check for the existence of the given key on all object, and return false if not all of them have this key.
- some:
It will check if at least one object has that key and if there is it already returns true.
回答4:
If you just want a true/false to determine if the element is in there, use 'some'. It returns true/false.
const arr = [{ id: 1, foo: 'bar' }, { id: 2 }];
var key = 'foo';
var isInArray= arr.some(function(val, i) {
return val[i][key];
});
回答5:
You could use Array#some
var arr = [{ id: 1, foo: 'bar' }, { id: 2 }],
result = arr.some(o => 'foo' in o);
console.log(result);
来源:https://stackoverflow.com/questions/42074997/in-an-array-with-objects-check-if-a-key-exists-in-any-of-those-objects