DEV Community

Matt Ellen
Matt Ellen

Posted on

Answer: Flatten nested object/array in javascript

I answered this question with a neat little algorithm.

The premise of the question is to turn this:

[{ a: 2, b: [{ c: 3, d: [{e: 4, f: 5}, {e: 5,f: 6}]}, 
             { c: 4, d: [{e: 7, f: 8}]}
            ]
}]
Enter fullscreen mode Exit fullscreen mode

into this:

[{a:2,c:3,e:4,f:5}, {a:2,c:3,e:5,f:6}, {a:2,c:4,e:7,f:8}]
Enter fullscreen mode Exit fullscreen mode

It was surprisingly tricky. My first few attempts always produced duplicates. I considered creating a blank result object "template" and then filling one out for every array, but that sounded like too much work.

In the end I recurse for every array and then when the call comes back I combine the returned array with the current array in a way that won't overwrite existing properties.

Take a look!

It's a bit of a behemoth, and it doesn't preserve the keys' order, but it does work with no duplicates.

It is recursive, so watch out for the call stack.

  • First, loop through the items in the array,
  • If an item is an array, make a recursive call
    • On returning…

Discussion (0)