话不多说直接上代码
parentTree(arr) { //arr 所有的树数据 id 某个子节点的id
let temp = {}
let tree = {}
arr.forEach(item=>{
temp[item.id] =item
})
let tempKeys = Object.keys(temp)
tempKeys.forEach(key=>{
let item =temp[key]
let _itemPID = item.p_id
let parentItemByPid= temp[_itemPID]
if(parentItemByPid){
if(!parentItemByPid.children) {
parentItemByPid.children = []
}
parentItemByPid.children.push(item)
}else{
tree[item.id] = item
}
})
return Object.keys(tree).map(key =>tree[key])
}