一维数组转换为多维数组--高级写法

741 阅读1分钟
function listToTree(data) {
    let arr = JSON.parse(JSON.stringify(data));
    const listChildren = (obj, filter) => {
        [arr, obj.children] = arr.reduce((res, val) => {if (filter(val)) res[1].push(val); else res[0].push(val);return res;}, [[], []]);
        obj.children.forEach(val => {
            if (arr.length) listChildren(val, obj => obj.pId === val.id);
        });
    };
    const tree = {};
    listChildren(tree, val => arr.findIndex(i => i.id === val.pId) === -1);// 找出父元素
    return tree.children;
}

let array = [
    {
        id:1,
        name:"ceshi",
        pId:9999
    },
    {
        id:2,
        name:"ceshi2",
        pId: 9999
    },
    {
        id:3,
        name:"sahd",
        pId:1
    },
    {
        id:4,
        name:"ooopkhh",
        pId:2,
    }
]

console.log(listToTree(array))