UPDATE: I noticed that there has been a correction made to the original post, rendering this answer no longer relevant. The array structure you intended to define seems to have changed. I will keep my original response for educational purposes, but I recommend checking out @terry-lennox's answer here
The initial array format you provided is incorrect as it implies both elements have the following structure:
foo: {
name: 'One',
value: 10
}
This format is not valid. It appears you intended for each element to be an object itself, like so:
{
foo: {
name: 'One',
value: 10
}
}
Therefore, the revised array would look like this:
[{
foo: {
name: 'One',
value: 10
}
}, {
bar: {
name: 'Two',
value: 20
}
}]
With this fixed structure, your objective is to extract the object associated with the first key in every element of the array. This can be achieved by:
yourArray.map(item => item[Object.keys(item)[0]]);
The map()
function will generate a new array by executing the specified function for each element in yourArray
. The function within map()
simply returns the value of the first key for each item.