DEV Community

Matt Ellen-Tsivintzeli
Matt Ellen-Tsivintzeli

Posted on

2 2

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…

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay