SOURCE

const entries = [
    {
        "province": "浙江", "city": "杭州", "name": "西湖"
    }, {
        "province": "四川", "city": "成都", "name": "锦里"
    }, {
        "province": "四川", "city": "成都", "name": "方所"
    }, {
        "province": "四川", "city": "阿坝", "name": "九寨沟"
    }
];

const level = ["province", "city", "name"];

function listToTree(list, level) {
    const map = []
    
    list.forEach(item => {
        pushTo(map, item, 0)
    })

    function pushTo(arr, obj, levIdx) {
        const o = {
            value: obj[level[levIdx]],
            children: []
        }

        const hasItem = arr.find(item => item.value === obj[level[levIdx]])
        let nowArr;

        if (hasItem) {
            nowArr = hasItem.children
        } else {
            arr.push(o)
            nowArr = o.children
        }

        if (levIdx === level.length - 1) delete o.children;
        levIdx++;

        if (levIdx < level.length) {
            pushTo(nowArr, obj, levIdx)
        }
    }

    return map;
}

console.log(listToTree(entries, level))

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},
]

function t(arr) {
    const map = {};
    const result = [];

    arr.forEach(item => {
        map[item.id] = item
    })

    arr.forEach(item => {
        if (item.pid === 0) {
            result.push(item)
        } else {
            map[item.pid]['children']
                ? map[item.pid]['children'].push(item)
                : map[item.pid]['children'] = [item]
        }
    })

    return result
}
// console.log(t(arr))
console 命令行工具 X clear

                    
>
console