我希望能够从扁平数组中构建一棵树状数组:
以下是扁平数组:
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"}
];
我希望将其转换为以下数组:
NB: id = 节点ID; pid = 父节点ID。
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'
}]
}]
}];
我尝试使用递归函数来实现期望的结果,但我正在寻找更好的方法。谢谢您的回复。