将扁平化的数组处理为树结构数据,我们可以利用对象来处理,对象的复制是浅拷贝,指向相同的内存地址:
var arr = [
{
id: 0,
pid: -1,
name: 'sadas'
},
{
id: 1,
pid: -1,
name: 'sadas'
},
{
id: 2,
pid: -1,
name: 'sadas'
},
{
id: 3,
pid: -1,
name: 'sadas'
},
{
id: 4,
pid: 1,
name: 'sadas'
},
{
id: 5,
pid: 1,
name: 'sadas'
}
]
var obj = {}
arr.map((v, i) => {
if (obj[v.pid]) {
if (obj[v.pid].children) {
obj[v.pid].children.push(v)
} else{
obj[v.pid].children = [v]
}
} else{
obj[v.pid] = {
children: [v]
}
} if (obj[v.id]) {
v.children = obj[v.id].children
}
obj[v.id] = v
})
console.log(obj[-1])