I have a flat array where each node has an ID and an array of the IDs of its children:
[
{id: 1, children: [2, 3]},
{id: 2, children: []},
{id: 3, children: [4]},
{id: 4, children: []},
{id: 5, children: []},
]
How can I, preferably in Javascript, create a hierarchy with the actual objects as nested children instead of just their IDs?
[
{id: 1, children: [
{id: 2, children: []},
{id: 3, children: [
{id: 4, children: []}
]}
]},
{id: 5, children: []},
]
I have tried the following but it only works the first layer:
function getHierarchyFromFlatArray(nodes) {
const nodeById = new Map(nodes.map(el => [el.id, el]))
for (const node of nodes) {
node.children = node.children.map(id => {
let val = nodeById.get(id)
let idx = nodes.findIndex(item => item.id=== id)
nodes.splice(idx, 1)
return val
})
}
return nodes
}