Skip to content
Advertisement

Flatten nested JavaScript object

I have a nested object and I want to flatten/map it into a single-layered, table-like object.

JavaScript

From that, I want to get something like this:

JavaScript

Sure, I could simply iterate over the object with two for loops and put the result info a separate array, but I wonder, if there is a simpler solution. I already tried to play around with flatMap. It works, if I only want the c portion of my nested object, but I don’t know how to map a and b to this object.

As some of you asked for some working code, this should do it (untested):

JavaScript

The question is, if there is a functional one-liner or even another, better approach. In reality, my object consists of four layers and the nested for loops become messy quite fast.

Advertisement

Answer

Ideally a solution would require something to tell how far down to start classing the object as been a full object, a simple solution is just to pass the level you want. If you don’t want to pass the level, you could do a check and if none of the properties have array’s, then you would class this as a complete record, but of course that logic is something you would need to confirm.

If you want a generic version that works with multiple levels were you pass the level & using recursion you could do something like this ->

JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement