Data to be converted:

[{id: 10122.name:'Top-level node'.parentId: 0}, {id: 10123.name:'child'.parentId: 10122}, {id: 10123.name:'sun class'.parentId: 10122}]
Copy the code

Target data:

[{
id: 10122.name:'Top-level node'.parentId: 0.children:[id: 10123.name:'child'.parentId: 10122.children: [{id: 10123.name:'sun class'.parentId: 10122}}]]]Copy the code

{id:{item}} {children} {id:{item}} {children} {id:{item}} {children}

Implementation code:

from(list = [], props = {id: 'id', parentId: 'parentId'}) {
        let map = {};
        let tree = [];

        list.forEach(item= > {
            map[item[props.id]] = item;
        });

        list.forEach(item= > {
            if (item[props.parentId] && map[item[props.parentId]]) {
                if (!Array.isArray(map[item[props.parentId]]['children'])) {
                    map[item[props.parentId]]['children'] = [];
                }
                map[item[props.parentId]]['children'].push(map[item[props.id]]);
            } else{ tree.push(map[item[props.id]]); }}); map =null;
        return tree;
    },
Copy the code