Skip to content
Advertisement

transfer flat object to nested object (javascript)

i am getting a flat object of cms navigation and want to transfer it to a nested object.
The level describes the position of the element in the tree.
Whenever there are subelements they should be stored under a new subCategory.
In every level could be multiple elements.
For example two level 1 categories (“shop service” and “information”).

The flat object:

JavaScript

The result should be a nested object with this structure

JavaScript

I tried serveral ways, but can’t make it.

Thanks in advance.
Stefan

Advertisement

Answer

You can use a stack to track where you are in the tree while it is being constructed.

It is strange that level has a string data type while clearly its meaning is numeric.

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