1
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


消息
80 声望1 粉丝

一个无趣的人