这应该是性能最优的数组转树结构方法

1,968 阅读2分钟

前端使用树插件是一个非常常见的使用场景。树插件的数据格式在我使用过的插件都是一样的。 而这个数据格式是由后端组装好返回给前端还是前端自己组装,这个问题在前端和后端也经常拿来撕逼。

大多数情况下后端会组装好,也有一部分前端自己处理,早之前我合作过的一个后端提出了一个观点, 浏览器是每一个用户都有的,服务器是所有用户共同访问的,后端递归遍历组装树数据比前端处理更耗费性能。

那时候我居然无言以对,几十条数据组装成树结构的数据居然能牵扯到服务器性能问题,那这个服务器还能做什么?

也不是想讨论由前端还是后端处理的问题,这种简单的东西,只要商量一下,约定好了,哪一边处理都是可以的。

现在网上数组转树结构的方法很多,都能够得到想要的结果,今天分享这个方法,我认为应该是性能最优的:

let arr = [
  {id: 1, name: '部门1', pid: 0},
  {id: 2, name: '部门2', pid: 3},
  {id: 3, name: '部门3', pid: 1},
  {id: 4, name: '部门3', pid: 0},
  {id: 5, name: '部门4', pid: 4},
  {id: 6, name: '部门5', pid: 0},
  {id: 7, name: '部门5', pid: 6},
  {id: 8, name: '部门5', pid: 7},
]

function arrayToTree(data) {
  let result = [];
  let itemMap = {};
  for (let i = 0; i < data.length; i++) {
    let item = data[i];
    let id = item.id;
    let pid = item.parentResourceId;
    if(!itemMap[id]){
      itemMap[id] = {
        children: []
      }
    }
    itemMap[id] = {
      ...item,
      children: itemMap[id]['children']
    }
    let treeItem = itemMap[id];
    if(pid === 0){
      result.push(treeItem);
    }else{
      if(!itemMap[pid]){
        itemMap[pid] = {
          children: []
        }
      }
      itemMap[pid]['children'].push(treeItem);
    }
  }
  return result;
}
console.log(arrayToTree(arr));

得到的结果:

[    {        "id": 1,        "name": "部门1",        "pid": 0,        "children": [            {                "id": 2,                "name": "部门2",                "pid": 1,                "children": []
            },
            {
                "id": 3,
                "name": "部门3",
                "pid": 1,
                "children": []
            }
        ]
    },
    {
        "id": 4,
        "name": "部门3",
        "pid": 0,
        "children": [
            {
                "id": 5,
                "name": "部门4",
                "pid": 4,
                "children": []
            }
        ]
    },
    {
        "id": 6,
        "name": "部门5",
        "pid": 0,
        "children": [
            {
                "id": 7,
                "name": "部门5",
                "pid": 6,
                "children": [
                    {
                        "id": 8,
                        "name": "部门5",
                        "pid": 7,
                        "children": []
                    }
                ]
            }
        ]
    }
]

思路很简单,维护一个json的map,每一个id都有自己的children和本身的数据, 把属于这个id的pid项都存入children数组,因为json的map都是对象,浅拷贝下, 只要是属于这个对象的children数组都会是同一个。可以打印itemMap看看每一个id对应的数据。

欢迎关注 coding个人笔记 订阅号