You could use the level property for indicating the nested position in a helper array. Then iterate the data and build children nodes if necessary.
function getTree(array) {
var levels = [{}];
array.forEach(function (a) {
levels.length = a.level;
levels[a.level - 1].nodes = levels[a.level - 1].nodes || [];
levels[a.level - 1].nodes.push(a);
levels[a.level] = a;
});
return levels[0].nodes;
}
console.log(getTree([{ 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 }]));
console.log(getTree([{ id: 1, name: 'Node 1', level: 1 }, { id: 2, name: 'Node 1.1', level: 2 }, { id: 3, name: 'Node 1.1.1', level: 3 }, { id: 4, name: 'Node 1.1.1.1', level: 4 }, { id: 5, name: 'Node 1.2', level: 2 }, { id: 6, name: 'Node 1.2.1', level: 3 }, ]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
10
solved Generate Tree from flat Array javascript