一维数组转为tree

法一:递归实现

/**
 let arr = [
  {id: 1, name: '部门1', pid: 0},
  {id: 2, name: '部门2', pid: 1},
  {id: 3, name: '部门3', pid: 1},
  {id: 4, name: '部门4', pid: 3},
  {id: 5, name: '部门5', pid: 4},
 ]
 ---------------->
 var tree =[
  {
    "id": 1,
    "name": "部门1",
    "pid": 0,
    "children": [
      {
        "id": 2,
        "name": "部门2",
        "pid": 1,
        "children": []
      },
      {
        "id": 3,
        "name": "部门3",
        "pid": 1,
        "children": [
          // 结果 ,,,
        ]
      }
    ]
  }
]
 */

function findParent(res, obj) {
  if (Array.isArray(res)) {
    for (let i = 0; i < res.length; i++) {
      const item = res[i];
      if (item.id === obj.pid) {
        Array.isArray(item['children']) ? item['children'].push(obj) : item['children'] = [obj]
      } else {
        if (item['children'] && item['children'].length) {
          findParent(item['children'], obj)
        }
      }
    }
  }
}

function toTree(arr) {
  arr = arr.sort((a, b) => a.pid - b.pid) // 按照pid排序
  let res = []

  for (let i = 0; i < arr.length; i++) {
    const obj = arr[i];
    if (obj.pid == 0) { // 将第一层树插入
      res.push(obj)
    } else {
      findParent(res, obj) // 将obj插入到res树中
    }
  }

  return res
}

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

console.log(toTree(arr));

法二:空间换取时间

function arrayToTree(items) {
      const result = []; // 存放结果集
      const itemMap = {}; //
      for (const item of items) {
        const id = item.id;
        const pid = item.pid;

        // 给当前节点添加children属性
        itemMap[id] = {
          ...item,
          children: !itemMap[id] ? [] : itemMap[id]["children"],
        };

        // 记录当前指针:内存地址
        const treeItem = itemMap[id];

        if (pid === 0) {
          // 将pid为0的加入到第一层中
          result.push(treeItem);
        } else {
          if (!itemMap[pid]) {
            itemMap[pid] = {
              children: [],
            };
          }
          // 将当前节点对象,插入到对应的pid的children数组末尾
          itemMap[pid].children.push(treeItem);
        }
      }
      return result;
    }

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

    console.log(arrayToTree(arr));
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值