Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a terse es6 way of flattening a nested object?

For example, turn this:

const enums = { ip: 'ip', er: 'er' };

const obj = {
  somethingNotNeeded: {...},
  er: [
    { a: 1},
    { b: 2}
  ],
  somethingElseNotNeeded: {...},
  ip: [
    { a: 1},
    { b: 2}
  ]
}

Into this:

[
  { a: 1},
  { b: 2},
  { a: 1},
  { b: 2}
]

I'm already doing this in a roundabout way by declaring an enum object of the types i want (er, ip) then doing a forEach (lodash) loop on obj checking if the keys aren't in the enum and delete them off the original obj. Then having just the objects I want, I do two nested forEach loops concatenating the results to a new object using object rest spread...

I'm almost entirely sure there's a better way of doing this but I didn't think of it today.

like image 455
kyle Avatar asked Dec 10 '25 11:12

kyle


1 Answers

Get the enums properties with Object.values() (or Object.keys() if they are always identical). Use Array.map() to iterate the array of property names, and extract their values from obj. Flatten the array of arrays by spreading it into Array.concat():

const enums = { ip: 'ip', er: 'er' };

const obj = {
  somethingNotNeeded: {},
  er: [
    { a: 1},
    { b: 2}
  ],
  somethingElseNotNeeded: {},
  ip: [
    { a: 1},
    { b: 2}
  ]
};

const result = [].concat(...Object.values(enums).map(p => obj[p]));

console.log(result);
like image 70
Ori Drori Avatar answered Dec 13 '25 00:12

Ori Drori



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!