1.递归方法
export function tranListIoTreeData(list, rootvalue) {
const arr = []
list.forEach(item => {
if (item.pid === rootvalue) {
const children = tranListIoTreeData(list, item.id)
if (children.length) {
item.children = children
}
arr.push(item)
}
})
return arr
}
2.非递归
非递归的形式 数组装换成树状图
var arr = [
{ id: 2, pid: 1},
{ id: 1, pid: 0},
列表转树 不使用递归方式
function list2tree(list){
const arr =[]
list.forEach((v)=>{
const newList = list.filter((k)=>k.id !==v.id);
const root = newList.find((t)=>t.id === v.pid);
if(!root){
arr.push(v)
}
const children = newList.filter((k)=>k.pid === v.id);
if(children.length>0){
v.children = children
}else{
v.children = []
}
});
return arr;
}
const list = list2tree(arr)