SOURCE

const list = [
    { key: 1, data: 'A', parentKey: 0 },
    { key: 2, data: 'B', parentKey: 0 },
    { key: 3, data: 'C', parentKey: 1 },
    { key: 4, data: 'D', parentKey: 1 },
    { key: 5, data: 'E', parentKey: 2 },
    { key: 6, data: 'F', parentKey: 3 },
    { key: 7, data: 'G', parentKey: 2 },
    { key: 8, data: 'H', parentKey: 4 },
];

/* 
作者:shell0108
链接:https://www.nowcoder.com/discuss/869596?type=post&order=recall&pos=&page=0&ncTraceId=&channel=-1&source_id=search_post_nctrack&subType=2&gio_id=4B11D26016AC8D56CAC57B6E316F3069-1647866758531
来源:牛客网

/** 
[ 
    { 
        key: 1, 
        data: 'A', 
        parentKey: 0, 
        children: [ 
            { key: 3, data: 'C', parentKey: 1, children: [{ key: 6, data: 'F', parentKey: 3 }] }, 
            { key: 4, data: 'D', parentKey: 1, children: [{ key: 8, data: 'H', parentKey: 4 }] }, 
        ], 
    }, 
    { 
        key: 2, 
        data: 'B', 
        parentKey: 0, 
        children: [ 
            { key: 5, data: 'E', parentKey: 2 }, 
            { key: 7, data: 'G', parentKey: 2 }, 
        ], 
    }, 
];

*/

function test(list, curParentKey) {
    const tempList = list.filter((object) => object.parentKey === curParentKey)
    const ret = []
    for (let i = 0; i < tempList.length; i++) {
        const temp = {}
        Object.assign(temp, tempList[i])
        const children = test(list, tempList[i].key)
        if (children.length) {
            temp.children = children
        }
        ret.push(temp)
    }
    return ret
}

console.log(JSON.stringify(test(list, 0), null, 4))
console 命令行工具 X clear

                    
>
console