let data=[
{pid:'',name:'父节点1',id:1},
{pid:'',name:'父节点2',id:2},
{pid:1,name:'父节点1-字节点1',id:3},
{pid:1,name:'父节点1-字节点2',id:4},
{pid:2,name:'父节点2-字节点1',id:5},
{pid:2,name:'父节点2-字节点2',id:6},
{pid:6,name:'父节点2-字节点2-子节点',id:7},
{pid:7,name:'父节点2-字节点2-子节点-子节点',id:8},
]
let result = []
// 遍历 data 获取父节点
function getTree(){
data.forEach(item=>{
if(item.pid===''){
item.children=getChildrenList(item.id)
result.push(item)
}
})
}
getTree()
//递归获取子节点
function getChildrenList(id){
let res=[]
data.forEach(item=>{
//遍历节点 如果该节点pid 等于 id 则递归
if(item.pid===id){
item.children=getChildrenList(item.id)
res.push(item)
}
})
return res
}
树结构转换
最新推荐文章于 2024-10-25 16:58:12 发布