const arr=[
{ id: '01', pid: '', name: '老王', children: [] },
{ id: '02', pid: '01', name: '小王', children: [] },
{ id: '03', pid: '02', name: '小小王', children: [] },
{ id: '04', pid: '', name: '小张', children: [] },
{ id: '05', pid: '04', name: '小小张', children: [] }
]
function tranListToTreeData(arr){
const newarr=[]
// 1. 构建一个字典:能够快速根据id找到对象。
const map={}
arr.forEach(item=>{
// 为了计算方便,统一添加children
map.children=[]
// 构建一个字典
const key=item.id
item[key]=item
})
// 2. 对于arr中的每一项
arr.forEach(item=>{
const partent=item.pid
if(partent){
// 如果它有父级,把当前对象添加父级元素的children中
partent.children.push(item)
}else{
// 如果它没有父级(pid:''),直接添加到newArr
newarr.push(item)
}
})
return newarr
}