json数据生成树

形成树

var data = [
  {id:1,name:'json',parentId:0},
  {id:2,name:'json',parentId:0},
  {id:3,name:'json',parentId:1},
  {id:4,name:'json',parentId:2},
  {id:5,name:'json',parentId:3},
  {id:6,name:'json',parentId:4},
  {id:7,name:'json',parentId:5},
  {id:8,name:'json',parentId:5},
  {id:9,name:'json',parentId:8},
  {id:10,name:'json',parentId:2},
]

var buildTree = (data) => {
  data.sort((a, b) => a.parentId - b.parentId)
  while(data[data.length - 1].parentId > 0){
    let cur = data.pop()
    let parent = data.filter((node)=>{
      return node.id == cur.parentId
    })
    if(parent.length == 1){
      parent[0].children = []
      parent[0].children.push(cur)
    }
  }
  return data
}

 

上一篇:Python 爬虫(Spider)基础 - 大约16万字


下一篇:实现线性结构转树形结构(生成无限层级菜单)