arr2tree

数组转树结构数据。

function arr2tree (arr) {
    const arrObj = {};
    arr.forEach(item => {
        arrObj[item.id] = {
            ...item,
            children: [],
        };
    });

    const tree = [];
    arr.forEach(item => {
        if(!item.pid) {
            tree.push(arrObj[item.id]);
        } else {
            arrObj[item.pid].children.push(arrObj[item.id]);
        }
    })
    return tree;
}

const arr = [
    {
        id: 1,
        pid: null,
        text: '1',
    },
    {
        id: 2,
        pid: 1,
        text: '2'
    },
    {
        id: 3,
        pid: 1,
        text: '3'
    }
]

const a = arr2tree(arr);
console.dir(a);

你可能感兴趣的:(js,js)