6

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?

5 Answers 5

5

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

3

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);

3 Comments

This will not work if searched property value is falsy (e.g foo: 0)
@bartekfr in my use case it's not an issue (it will always be an integer above 0), but kudos for pointing that out.
Updated the answer. It originally looked like the OP was looking for "truthy" property values, not that he was looking for the existence of the property.
1

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];
});

Comments

0

You could use Array#some

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

console.log(result);

1 Comment

Shouldn't this be some instead?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.