JS将扁平化的数据处理成Tree结构

let jsonData= [
  { id:1,  parentId:0, name:"一级菜单A" },
  { id:2, parentId:0, name:"一级菜单B"},
  { id:3, parentId:0, name:"一级菜单C"},
  { id:4, parentId:1, name:"二级菜单A-A"},
  { id:5, parentId:1, name:"二级菜单A-B"},
  { id:6, parentId:2, name:"二级菜单B-A"},
  { id:7, parentId:4, name:"三级菜单A-A-A"},
  { id:8, parentId:7, name:"四级菜单A-A-A-A"},
  { id:9, parentId:8, name:"五级菜单A-A-A-A-A"},
];
将上述扁平化数据转化成树形结构
function formatTree(obj){
  let copyedObj = JSON.parse(JSON.stringify(obj)) //深拷贝源数据
  return copyedObj.filter(parent=>{
    let findChildren = copyedObj.filter(child=>{
      return parent.id === child.parentId
    })
    findChildren.length>0 ? parent.children = findChildren : parent.children = []
    return parent.parentId == 0 //返回顶层,依据实际情况判断这里的返回值
  })
}
}
console.log(JSON.stringify(formatTree(jsonData),null,3))
[
  {
    "id": 1,
    "parentId": 0,
    "name": "一级菜单A",
    "children": [{
      "id": 4,
      "parentId": 1,
      "name": "二级菜单A-A",
      "children": [{
        "id": 7,
        "parentId": 4,
        "name": "三级菜单A-A-A",
        "children": [{
          "id": 8,
          "parentId": 7,
          "name": "四级菜单A-A-A-A",
          "children": [{
            "id": 9,
            "parentId": 8,
            "name": "五级菜单A-A-A-A-A",
            "children": []
          }]
        }]
      }]
    },
    {
      "id": 5,
      "parentId": 1,
      "name": "二级菜单A-B",
      "children": []
    }]
  },
  {
    "id": 2,
    "parentId": 0,
    "name": "一级菜单B",
    "children": [{
      "id": 6,
      "parentId": 2,
      "name": "二级菜单B-A",
      "children": []
    }]
  },
  {
    "id": 3,
    "parentId": 0,
    "name": "一级菜单C",
    "children": []
  }
]

 

posted @ 2019-07-16 16:31  杰哥斯坦森  阅读(2008)  评论(0编辑  收藏  举报