SOURCE

const { isEmpty, groupBy,cloneDeep } = _

const formatTree = (list) => {
    if (_.isEmpty(list)) {
        return [];
    }
    return list.reduce((resultList, l) => {
        console.log('--------------------------')
        let selfIndex, parent;
        resultList.forEach((result, index) => {
            if (result.id === l.id) {
                selfIndex = index
            } else if (result.id === l.parentId) {
                parent = result
            }
        })
        console.log(l,selfIndex,parent)
        if (isEmpty(parent)) {
            return resultList
        }
        // 遍历children
        parent.children = (parent.children || []).concat(l)
        resultList.splice(selfIndex,1)
        console.log(cloneDeep(resultList))
        return resultList
    }, cloneDeep(list))

};

console.log(formatTree([
    {
        "id": 1,
        "parentId": null,
        "root": true
    },
    {
        "id": 2,
        "parentId": 1,
        "root": false
    },
    {
        "id": 3,
        "parentId": 1,
        "root": false
    },
    {
        "id": 4,
        "parentId": 2,
        "root": false
    },
    {
        "id": 5,
        "tenantId": 1,
        "name": "bg-1-2",
        "description": "业务组1-2",
        "parentId": 2,
        "homepageUrl": null,
        "homepageChildFirst": true,
        "roles": null,
        "defaultSelect": false,
        "recursive": null,
        "root": false
    },
    {
        "id": 6,
        "parentId": 3,
        "root": false
    },
    {
        "id": 34,
        "parentId": 1,
        "root": false
    },
    {
        "id": 35,
        "parentId": 34,
        "root": false
    },
    {
        "id": 36,
        // "parentId": 345,
        "root": false
    }
]))
console 命令行工具 X clear

                    
>
console