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?
You can use Array#some
var arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
result = arr.some(o => 'foo' in o)
console.log(result)
every()
and some()
It will check for the existence of the given key on all object, and return false if not all of them have this key.
It will check if at least one object has that key and if there is it already returns true.
const arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
var result = arr.some((value, index) => {
return value.hasOwnProperty('bar')
});
console.log(result);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With