I have data like so:
data = [
{
"foo": {"name":"foo-name"},
"bar": {"name":"bar-name"}
},
{
"baz": {"name":"baz-name"}
}
]
and my desired output would be:
[
{ "foo": {"name":"foo-name"}},
{ "bar": {"name":"bar-name"}},
{ "baz": {"name":"baz-name"}}
]
How do I get this structure? I tried using concat, but realized that it doesn't work as we are dealing with nested objects and not nested arrays. Then I tried iterating in different ways, but not achieving what I want. One try was the following:
const newData = data.map((x) => {
return Object.keys(x).map(el => {
return {[el]: x};
})
})
But that just made it more nested.
You can use flatMap
let data = [{"foo": {"name":"foo-name"},"bar": {"name":"bar-name"}},{"baz": {"name":"baz-name"}}]
let final = data.flatMap(a => Object.entries(a).map(([k, v]) => ({
[k]: v
})))
console.log(final)
One option is to reduce into an array, iterating over the entries of each object and pushing them to the accumulator:
const data = [
{
"foo": {"name":"foo-name"},
"bar": {"name":"bar-name"}
},
{
"baz": {"name":"baz-name"}
}
];
const output = data.reduce((a, obj) => {
Object.entries(obj).forEach(([key, val]) => {
a.push({ [key]: val });
});
return a;
}, []);
console.log(output);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With