Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flatten array of nested objects

Tags:

javascript

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.

like image 687
DRNR Avatar asked Jun 30 '26 15:06

DRNR


2 Answers

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)
like image 76
Code Maniac Avatar answered Jul 03 '26 03:07

Code Maniac


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);
like image 24
CertainPerformance Avatar answered Jul 03 '26 05:07

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!