js 多层菜单递归

思路

首先遍历一遍data找到顶级菜单(pid=0)存入res中,然后遍历res,为每一项添加children属性,用每一项的id作为pid查找它的子元素,没有则退出并删除children,不断递归即可

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.cosdk.com/archives/1569