-1

I need to find out if an array of a JS object includes an object with a specific key.

I am using,

my_array.filter((e) => Object.keys(e).includes(my_key)).length > 0

but there must be a way to do it simpler.

Any suggestions in addition to Check if array of objects contain certain key ?

0

2 Answers 2

0

Instead of .filter(…).length > 0, use .some(…).

Instead of Object.keys(…).includes(…), use … in … (or Object.hasOwn(…, …) if you need to ignore inherited properties).

So

my_array.some(e => my_key in e)
Sign up to request clarification or add additional context in comments.

Comments

0

instead of filter use some, already returns true or false and it shortcircuits as soon as it finds the first

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.