let arr =[{id:"01",name:"张大大",pid:"",job:"项目经理"},{id:"02",name:"小亮",pid:"01",job:"产品leader"},{id:"03",name:"小丽",pid:"02",job:"产品经理"},{id:"04",name:"大光",pid:"02",job:"产品经理"},]//方法一functiontoTree(arr){let parent = arr.filter(item=>!item.pid)let childs = arr.filter(item=> item.pid)translate(parent , childs )functiontranslate(parents,childs){for(let i in parents){
parents[i].childs =[]for(let j in childs){if(parents[i].id === childs[j].pid){
parents[i].childs.push(childs[j])let list =JSON.parse(JSON.stringify(childs))
list.slice(j,1)translate([childs[j]], list)}}}}return parent
}// 方法二functiontoTree(arr){let res =[]let map ={}
arr.forEach(item=>{
map[item.id]= item
}
arr.forEach(item=>{let parent = map[item.pid]if(parent){
parent.childs = parent.childs ? parent.childs.push(item): parent.childs =[item]}else{
res.push(item)}}}
2.根据id查找tree中的节点和路径
let tree ={id:1,name:"company",children:[{id:2,name:"group1",children:[{id:3,name:'dept1'},{id:5,name:'dept2',children:[{id:6,name:'user1'}]},]},{id:4,name:"gropu2"},]}functiongetPathRoute(tree, id, path){let arr = Array.isArray(tree)? tree :[tree]if(!path){
path =[]}for(let i in tree){let tempPath =[...path]
tempPath.push(arr[i].name)if(arr[i].id === id){return tempPath
}else{returngetPathRoute(tree[i], id, tempPath)}}}