Does array include object with specific key?

Viewed 30

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?

2 Answers

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