Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In an array with objects, check if a key exists in any of those objects

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?

like image 759
nshoes Avatar asked Feb 06 '17 18:02

nshoes


2 Answers

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.

like image 172
Carlos Afonso Avatar answered Sep 24 '22 02:09

Carlos Afonso


const arr = [{ id: 1, foo: 'bar' }, { id: 2 }]
var result = arr.some((value, index) => {
    return value.hasOwnProperty('bar')
});
console.log(result);
like image 35
Bartek Fryzowicz Avatar answered Sep 25 '22 02:09

Bartek Fryzowicz