I have this data structure that show the depth of each node in the nested tree:
[
{
"name": "ELECTRONICS",
"depth": 0
},
{
"name": "TELEVISIONS",
"depth": 1
},
{
"name": "TUBE",
"depth": 2
},
{
"name": "PLASMA",
"depth": 2
},
{
"name": "GAME CONSOLES",
"depth": 1
},
{
"name": "MP3 PLAYERS",
"depth": 1
},
{
"name": "FLASH",
"depth": 2
}]
I would like to transform the previews data with JavaScript / node.js / Angular into a hierarchical JSON like this:
[{
"name": "ELECTRONICS",
"children": [
{
"name": "TELEVISIONS",
"children": [
{
"name": "TUBE"
},
{
"name": "PLASMA"
}]
},
{
"name": "GAME CONSOLES"
},
{
"name": "MP3 PLAYERS",
"children": [
{
"name": "FLASH"
}]
}]
}]
Here's the magic
I've assumed that if the depth of the next array element is equal it's a sibling, if it's minor it's a children and if it's bigger we don't have to add any more elements to this branch. So, I create a branch, if it's the same depth i add it to our parent, if depth is less, i create a new branch and if it's bigger i stop creating branches and adding children to "my" parent.
EDIT
I'd pick Nina Scholz's solution because it's easier to understand
You could use
Array#forEach
and an array for the reference to the depth.This may help