原始数组对象:
let arr = [
{ id: 1, name: "节点1", parentId: 0 },
{ id: 2, name: "节点2", parentId: 1 },
{ id: 3, name: "节点3", parentId: 1 },
{ id: 4, name: "节点4", parentId: 2 },
{ id: 5, name: "节点5", parentId: 3 },
{ id: 6, name: "节点6", parentId: 5 },
{ id: 7, name: "节点7", parentId: 6 },
{ id: 8, name: "节点8", parentId: 6 }
];
1、非递归算法
function listToTree(data){
let idObj={}
data.forEach(item => {
idObj[item.id]=item
})
let treeData=[]
data.forEach(item=>{
let parent=idObj[item.parentId]
if(parent){
parent.children=parent.children||[]
parent.children.push(item)
}else{
treeData.push(item)
}
})
return treeData
}
2、递归算法
function listToTreeLoop(data){
function getNode(id){
let arr=[]
data.forEach((item)=>{
if(item.parentId==id){
item.children=getNode(item.id)
arr.push(item)
}
})
return arr
}
return getNode(0)
}
处理结果: