My goal is to create a hierarchical tree structure from a flat array:
The original flat array looks like this:
nodes = [
{id: 1, pid: 0, name: "kpittu"},
{id: 2, pid: 0, name: "news"},
{id: 3, pid: 0, name: "menu"},
{id: 4, pid: 3, name: "node"},
{id: 5, pid: 4, name: "subnode"},
{id: 6, pid: 1, name: "cace"}
];
Note: id refers to node id and pid refers to parent node id.
The desired output should look like this:
nodes = [{
id: 1,
name: 'kpittu',
childs: [{
id: 6,
name: 'cace'
}]
}, {
id: 2,
name: 'news'
}, {
id: 3,
name: 'menu',
childs: [{
id: 4,
name: 'node',
childs: [{
id: 5,
name: 'subnode'
}]
}]
}];
I initially attempted to use a recursive function to achieve the desired outcome, but I am open to exploring alternative solutions. Thank you for your input.