将数组结构转为树结构数据

76 阅读1分钟

需要处理的数据

const datas = [
    {
        pid: '',
        id: 1,
        txt: 'hha1'
    },
    {
        pid: 1,
        id: 2,
        txt: 'hha2'
    },
    {
        pid: 1,
        id: 3,
        txt: 'hha3'
    },
    {
        pid: 2,
        id: 4,
        txt: 'hha4'
    },{
        pid: 3,
        id: 5,
        txt: 'hha5'
    }
]

转化之后的数据格式

image.png

编写转换方法

function arrayToTree(list, root) {
    let arr = [];
    // 增加代码健壮性,如果传入的数据非数组类型,阻断
    if (!Array.isArray(list)) {
        return;
    }
    list.forEach(item => {
        // 找到根节点
        if (item.pid === root) {
            // 该节点的子节点插入child里面
            item.child = arrayToTree(list, item.id);
            arr.push(item);
        }
    })
    return arr;
}