SOURCE

let list2tree = (list) => {
    let map = new Map();
    let res = [];
    for (let item of list) {
        map.set(item.id, item);
    }

    for (const entry of map) {
        let item = entry[1];
        if (item.pid && !map.has(item.pid)) {
            continue;
        }
        if (!item.pid) {
            res.push(item);
        } else {
            let parent = map.get(item.pid);
            if (!parent.children) {
                parent.children = [];
            }
            parent.children.push(item);
        }
    }
    return res;
}

console.log(list2tree([{ id: 1 }, { id: 2 }, { id: 22, pid: 2 },
{ id: 11, pid: 1 }, { id: 111, pid: 11 }, { id: 221, pid: 22 }]))
console 命令行工具 X clear

                    
>
console