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;
}

 

posted on 2019-10-31 11:06  刘世涛6192  阅读(282)  评论(0编辑  收藏  举报