若后端传回如下数据
[{name:'一级目录',id:'1',parentId:'0'},{name:'一级目录',id:'2',parentId:'0'},{name:'二级目录',id:'3',parentId:'1'},{name:'二级目录',id:'4',parentId:'2'},{name:'三级目录',id:'5',parentId:'3'}]
你要将其转为tree的结构。如何做呢?
function toTree(data,pid){ let res=[],temp; for(var i in data){ if(data[i].parentId == pid){ res.push(data[i]) temp = toTree(data,data[i].id); if(temp.length>0){ data[i].children=temp } } } return res; } console.log(toTree(list,0))