SOURCE

let source = [{name: '基金概况',pid: 1,id: 11,},
    {name: '基金介绍',pid: 11,id: 111,},
    {name: '基金经理',pid: 111,id: 1111,},
    {name: '基金回报',pid: 1,id: 12,},
    {name: '业绩表现',pid: 12,id: 112,}
]

function toTree(data) {
    let result = []
    if (!Array.isArray(data)) {
        return result
    }
    data.forEach(item => {
        delete item.children;
    });
    // ** 使用哈希表可以提高性能,不用每次都循环的去遍历当前节点的父节点
    let map = {};
    data.forEach(item => {
        map[item.id] = item;
    });
    data.forEach(item => {
        let parent = map[item.pid];
        if (parent) {
            // 处理父节点,因为是引用类型,所以给父节点添加了children属性,push到result中的节点也会添加children属性
            (parent.children || (parent.children = [])).push(item);
        } else {
            // 如果当前节点找不到该节点就需要将该节点push到result中,做一个区分
            result.push(item);
        }
    });
    return result;
}
let tree = toTree(source)
console.log(tree)
console 命令行工具 X clear

                    
>
console