1

例子:

const list = [
    { id: 0, name: "yx" },
    { id: 2, name: "yj", superId: 0 },
    { id: 4, name: "yd", superId: 0 },
    { id: 7, name: "yf", superId: 2 }
]

//转换为

const tree = {
    id: 0,
    name: "yx",
    children: [
        { 
            id: 2,
            name: "yj",
            children: [
                { id: 7, name: "yf" }
            ]
        },
        { id: 4, name: "yd" }
    ]
}

这种情况在前端渲染tree组件时时常会遇到

本人比较笨,思路就是遍历递归,比如这里没有superId就是root
root中创建为“children”的key,value就是遍历数组找到superId等于root的id的对象,然后递归root的children中的对象

每当将list中的一项添加到tree中对应的级别里时,从list中删除该项,
当list的length为0时就是递归的出口

这里用了lodash提供的工具函数,当然也可以splice(注意遍历时的下标)。

// ****** 对象数组 ==> 树
__arrToTree(arr, pid = "superiorId", id = "id") {
    let tree = [];
    _.remove(arr, item => {
        if (item[pid] === "0"){
            tree.push(item)
            return true
        }
        return false
    })
 // 递归
    const getChildren = (arr, tree, pid, id) => {
        if (!arr || !tree)return;
        tree.forEach(i => {
            _.remove(arr, j => {
                if (j[pid] === i[id]) {
                    i.children.push(j)
                    return true
                }
                return false
            })
            if (i.children.length === 0) {
                delete i.children;
            }else {
                getChildren(arr, i.children, pid, id)
            }
        }) 
    } 
    getChildren(arr, tree, pid, id)
    return tree
 }
// ******

丽塔y
29 声望2 粉丝

hey!