let dataArr = [
{
id:1,
name:'爷爷',
pid:0
},
{
id:2,
name:'爸爸',
pid:1
},
{
id:3,
name:'伯伯',
pid:1
},
{
id:4,
name:'辉',
pid:2
},
{
id:5,
name:'军',
pid:3
},
]
var toTree = function(tarArray){
var obj = {}
tarArray.map((item,index)=>{
obj[item.id] = item
})
var newArr = [];
for(var i=0;i<tarArray.length;i++){
var item = tarArray[i]
var parent = obj[item.pid]
if(parent){
if(parent.children){
parent.children.push(item)
}else{
parent.children = []
parent.children.push(item)
}
}else{
newArr.push(item)
}
}
console.log(newArr)
}
toTree (dataArr )
一维数组变成树结构
最新推荐文章于 2024-04-02 21:09:32 发布