js 一维数组转多维数组

效果图:
在这里插入图片描述

    //源数组
    const arrList = [{
      "id": 1,
      "code": "001",
      "name": "第一个",
      "parentCode": "",
    },
    {
      "id": 2,
      "code": "00101",
      "name": "第一个的二级",
      "parentCode": "001",
    },
    {
      "id": 3,
      "code": "0010101",
      "name": "第一个的三级",
      "parentCode": "00101",
    },
    {
      "id": 4,
      "code": "0010102",
      "name": "第一个的三级",
      "parentCode": "00101",
    },
    {
      "id": 3,
      "code": "002",
      "name": "第二个",
      "parentCode": "",
    },
    {
      "id": 6,
      "code": "00201",
      "name": "第二个的二级",
      "parentCode": "002",
    },
    {
      "id": 7,
      "code": "0020101",
      "name": "第二个的三级",
      "parentCode": "00201",
    },
    {
      "id": 8,
      "code": "0020102",
      "name": "第二个的三级",
      "parentCode": "00201",
    }]

    const listToTreeRegion = (list, fromKey = 'code', parentId = 'parentCode') => {
      const data = JSON.parse(JSON.stringify(list)); //浅浅的拷贝一份
      const result = []; //组装的结果
      const map = {}; //查找
      if (!Array.isArray(data)) return result;

      for (const item of data) {
        if (!map[item[fromKey]]) {
          map[item[fromKey]] = {
            ...item,
            children: []
          };
        }

        const parent = map[item[parentId]];
        if (parent) {
          // 如果item有parent,则将其添加到parent的children中  
          parent.children.push(map[item[fromKey]]);
        } else {
          // 如果没有parent,则将其添加到树的根级别  
          result.push(map[item[fromKey]]);
        }
      }
      return result;
    }

    const treeList = listToTreeRegion(arrList);
    console.log(treeList)
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值