function getTree(pid, arr, res) {
for (let i = 0; i < arr.length; i++) {
if (arr[i].pid == pid) {
res.push(arr[i])
arr.splice(i, 1)
i--
}
}
res.map(r => {
r.children = []
getTree(r.id, arr, r.children)
if (r.children.length == 0) {
delete r.children
}
})
return res
}
调用
let data = [
{id: 1, name: '菜单1', pid: 0},
{id: 2, name: '菜单1', pid: 1},
{id: 3, name: '菜单1', pid: 0},
{id: 4, name: '菜单1', pid: 2},
{id: 5, name: '菜单1', pid: 3},
]
console.log(getTree(0, data, [])) //pid为0表示最顶级菜单
结果
永久链接:https://blog.qianxiaoduan.com/archives/1569
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。