SOURCE

let list=[
    {
        name:'林爸爸',
        age:50,
        children:[
            {
                name:'女儿',
                age:20,
            },
            {
                name:'儿子',
                age:16,
            }
        ]

    },
    {
        name:'李妈妈',
        age:50,
        children:[
            {
                name:'李亿',
                age:20,
            },
            {
                name:'李帅',
                age:16,
            }
        ]

    }
]


function convertTree(data){
  let {label,value}={label:'name',value:'age'};
   return data.map(e=>{
      
       return {
           label:e[label],
           value:e[value],
           children:e.children!=null?convertTree(e.children):[]
       }
   })
 
}
let data=convertTree(list);
console.log(data)

// 扁平数据转为tree
var flattenData =[{
    id: 1,
    name: 'root',
}, {
    id: 2,
    name: '1-1',
    parentId: 1
}, {
    id: 3,
    name: '1-1-1',
    parentId: 2
}, {
    id: 4,
    name: '1-2',
    parentId: 1
}, {
    id: 5,
    name: '1-2-2',
    parentId: 4
}, {
    id: 6,
    name: '1-1-1-1',
    parentId: 3
}]

function convertTreeList(data,pid){
    let  result =[];let temp;
    for(let i=0; i<data.length;i++){
        if(data[i].parentId==pid){
            let obj={...data[i]};
            temp=convertTreeList(data,data[i].id)
            if(temp.length>0){
                obj.children=temp;
            }
            result.push(obj)
        }

    }

    return result;

}

let mlist=convertTreeList(flattenData);
console.log(mlist)
console 命令行工具 X clear

                    
>
console