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)?
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' } ]
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