Search code examples
javascriptarraysecmascript-5

Elegant way to select key in object of an array


Consider having the following json

[
{'key1': { ... }},
{'key2': { ... }},
{'key3': { ... }}
]

I want to extract the keys for those objects in an elegant way, the following code is working, but it seems ugly to me.

let result = objects.map(o => Object.keys(o))[0]

the [0] at the end because the returned value is an array of array


Solution

  • You can use .concat() and .map() methods to get the desired result:

    let data = [
      {'key1': { }},
      {'key2': { }},
      {'key3': { }}
    ];
    
    let result = [].concat(...data.map(Object.keys));
    
    console.log(result);

    References: