Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Transforming nested objects to an array

I have an object that contains other objects, such as:

let foo = {
  a: {
    b: {},
    c: {}
  },
  d: {
    e: {}
  }
};

Now I want to transform this into an array of objects, where the keys of the first two levels form a key / value pair, such as:

let transformedFoo = [
  { outer: 'a', inner: 'b' },
  { outer: 'a', inner: 'c' },
  { outer: 'd', inner: 'e' }
];

My current approach looks like this:

let fooTransformed = [];

Object.keys(foo).forEach(function (outerKey) {
  Object.keys(foo[outerKey]).forEach(function (innerKey) {
    fooTransformed.push({
      outer: outerKey,
      inner: innerKey
    });
  });
});

It works, but I think it's not "nice" (i.e., it's not nice to have two nested loops). Is there a better way on how to achieve this (I could imagine that there is a quite elegant purely functional solution, but I can't think of any)?

like image 920
Golo Roden Avatar asked Nov 19 '25 13:11

Golo Roden


1 Answers

Using map and reduce:

> Object.keys(foo).map(function(key) { 
      return Object.keys(foo[key]).map(function(val) {
          return {outer: key, inner: val} } ) 
      }).reduce(function(a,b) { return a.concat(b) })

[ { outer: 'a', inner: 'b' },
  { outer: 'a', inner: 'c' },
  { outer: 'd', inner: 'e' } ]
like image 133
tlehman Avatar answered Nov 22 '25 02:11

tlehman



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!