数组转成tree结构
- 方法一:
function tranListToTreeData(arr) {
const newArr = []
const map = {}
// 遍历arr数组的每一个对象 ,
arr.forEach(item => {
// 每一个对象都添加一个children属性,值为空数组
item.children = []
// 每一个对象的id取出来作为key
const key = item.id
// 把每一个对象作为key键的值,添加到map中
map[key] = item
})
console.log(map)
arr.forEach(item => {
// map[item.pid] 中 item.pid作为map的key map[item.pid] = value
// item: {id:"01", pid:"", "name":"老王" } {id:"02", pid:"01", "name":"小张" }
const parent = map[item.pid] // item.pid="01"则 map[01]={id:"01", pid:"", "name":"老王" }
console.log(parent)
if (parent) {
parent.children.push(item)
} else {
newArr.push(item)
}
})
return newArr
}