数组转tree arrToTree

数组转tree

let arr = [
        {id: 2, name: "部门2", pid: 1},
        {id: 1, name: "部门1", pid: 0},
        {id: 3, name: "部门3", pid: 1},
        {id: 4, name: "部门4", pid: 3},
        {id: 5, name: "部门5", pid: 4},
      ];
      console.log(arrtoTree(arr));
      function arrtoTree() {
        let map = new Map();
        let res = arr.map((item) => {
          return getChild(item, arr, map);
        });
        return res;
      }
      function getChild(params, arr, map) {
        //判断是否寻找过
        if (map.has(params.id)) {
          return map.get(params.id);
        }
        //寻找符合项
        let res = arr.filter((item) => item.pid === params.id);
        if (res.length > 0) {
          res = res.map((item) => {
            return getChild(item, arr, map);
          });
        }
        params.children = res;
        //缓存数据
        map.set(params.id, params);
        return params;
      }
posted @ 2021-08-10 13:03  黑黑哈哈  阅读(290)  评论(0编辑  收藏  举报