Skip to content
Advertisement

Convert array of flat objects to nested objects

I have the following array (that’s actually coming from a backend service):

JavaScript

where Item is:

JavaScript

In order to be compatible with a component that displays a tree (folder like) view, it needs to be transformed into:

JavaScript

where NestedItem is:

JavaScript

All I’ve tried so far is something like:

JavaScript

But this only gets the first level of children, of course (direct children of root nodes). It somehow needs to be recursive, but I have no idea how to accomplish that.

Advertisement

Answer

Making no assumptions about the order of the flattened array or how deep a nested object can go:

Array.prototype.reduce is flexible enough to get this done. If you are not familiar with Array.prototype.reduce I recommend reading this. You could accomplish this by doing the following.

I have two functions that rely on recursion here: findParent and checkLeftOvers. findParent attempts to find the objects parent and returns true or false based on whether it finds it. In my reducer I add the current value to the array of left overs if findParent returns false. If findParent returns true I call checkLeftOvers to see if any object in my array of left overs is the child of the object findParent just added.

Note: I added { id: 'b2-2-1', name: 'Item 2-2-1', parentId: 'b2-2'} to the flat array to demonstrate that this will go as deep as you’d like. I also reordered flat to demonstrate that this will work in that case as well. Hope this helps.

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