data = [ {id:1, pid:0}, {id:2, pid:1}, {id:3, pid:1}, {id:4, pid:3}, {id:5, pid:2}, {id:6, pid:0}, ] parents = {} data.forEach((v,k)=>{ console.log(k, v) if (!parents[v["pid"]]) { parents[v["pid"]] = [] } parents[v["pid"]].push(v) }) console.log(parents)
for(key in parents){
getChildsDem(parents[key])
}
function getChildsDem(val) {
val.forEach((v,k)=>{
if (!parents[v["id"]]) {
v.children = []
return false;
}
v.children = parents[v["id"]];
})
}
console.log(parents[0])//当前是返回树结构
function getChilds(id) { if (!parents[id]) { return [] } var childs = parents[id]; return childs; }