How do I transform an array?
I have an array of the form:
[
{
foo:{
name: 'One',
value: 10
},
bar: {
name: 'Two',
value: 20
}
}
]
I want to get an array of the form:
[
{
name: 'One',
value: 10
},
{
name: 'Two',
value: 20
}
]
Can I transform it with a map, for example? Or do I need another way?
Solution 1:
You can use Object.values() along with Array.flatMap()to get the required result:
let arr = [
{
foo:{
name: 'One',
value: 10
},
bar: {
name: 'Two',
value: 20
}
}
]
let result = arr.flatMap(obj => Object.values(obj));
console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Solution 2:
flatMap function is not supported by all versions, you can check this
you can try this function with supported array methods example:
function transform(arr) {
let empty = [];
arr.forEach(obj => {
const secondArr = Object.entries(obj);
empty.push(...secondArr.map(arr => arr[1]));
});
return empty;
}
here is an example in JSFiddle PlayGround
Solution 3:
EDIT: I saw that you corrected the original post, and this answer is not relevant anymore, because the array I guess you wanted to define is not what you actually wanted to. I'll leave my original answer for educational purposes, but to answer your question I would recommend to check @terry-lennox answer https://stackoverflow.com/a/70770819/12166040
The first array you specified is invalid: it would mean both elements have this shape:
foo: {
name: 'One',
value: 10
}
That's not a valid element. I guess you meant to every element be an object itself, like:
{
foo: {
name: 'One',
value: 10
}
}
So, the original array should be:
[{
foo: {
name: 'One',
value: 10
}
}, {
bar: {
name: 'Two',
value: 20
}
}]
Having this, your goal is to retrieve the object of the first key in every element of the array. You can do it this way:
yourArray.map(item => item[Object.keys(item)[0]]);
map()
will return a new array by running its function parameter for every element of yourArray
. And the function specified inside map()
just returns whatever is inside on the first key of every item.