Search code examples
javascriptarraysnested-object

Return all nested objects with specific keys


I have an array of objects in Javascript:

[
{a: 1, b: 2, c: 4},
{d: 10, a: 9, r: 2},
{c: 5, e: 2, j: 41}
]

I would like to return an array of all the objects that have the key name c by using the key name for the lookup.

What is the best way to accomplish this?


Solution

  • You can use filter method and hasOwnProperty

    const arr = [{a: 1, b: 2, c: 4},{d: 10, a: 9, r: 2},{c: 5, e: 2, j: 41}];
    const myArray = array.filter(e => e.hasOwnProperty('c'))