SOURCE

function list2tree(list, pid) {
    let tree = [];
    for (let i = 0; i < list.length; i++) {
        if (list[i].pid == pid) {
            tree.push(list[i]);
            list[i].children = list2tree(list, list[i].id)
        }
    }
    return tree;
}
let arr = [
    { id: 1, name: '部门1', pid: 0 },
    { id: 2, name: '部门2', pid: 1 },
    { id: 3, name: '部门3', pid: 1 },
    { id: 4, name: '部门4', pid: 3 },
    { id: 5, name: '部门5', pid: 4 },
]
console.log(list2tree(arr, 0));

console 命令行工具 X clear

                    
>
console