I have an array as follow
arr = [
{
id: 1,
name: 'Node1',
level: 1
},
{
id: 2,
name: 'Node2',
level: 2
},
{
id: 3,
name: 'Node3',
level: 3
},
{
id: 4,
name: 'Node4',
level: 4
},
{
id: 5,
name: 'Node5',
level: 5
},
];
I want to generate tree on basis of level.
Output should be
tree =
{
id: 1,
name: 'Node1',
level: 1,
nodes: {
id: 2,
name: 'Node2',
level: 2,
nodes : {
id: 3,
name: 'Node3',
level: 3,
nodes: {
id: 4,
name: 'Node4',
level: 4,
nodes : {
id: 5,
name: 'Node5',
level: 5,
nodes: []
}
}
}
}
}
whenever nodes = [], that means it's the last nodes. the order of array can be anything but tree should be built on basis of level.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…