合并多个树形结构数据并去重

问题场景

在项目中有父子项关联的页面或者组织,每个子项根据业务的实际情况对树形数据进行勾选。保存后,每个子项可以单独查看自己勾选的数据,父项可以查看所有子项数据的合集,所以就需要对每个子项的树形数据进行合并并且将重复的数据进行去重,最终展示为一个完整测树形结构。

实现方法

原始数据(多个树形数据)

const arr1 = [
  {
    id: 1,
    name: '1xx-xx',
    children: [
      {
        id: 2,
        name: '2xx-xx'
      },
      {
        id: 5,
        name: '5xx-xx',
        children: [
          {
            id: 6,
            name: '6xx-xx'
          }
        ]
      }
    ]
  },
  {
    id: 3,
    name: '3xx - xx'
  }
];

const arr2 = [
  {
    id: 1,
    name: '1xx-xx',
    children: [
      {
        id: 2,
        name: '2xx-xx'
      }
    ]
  },
  {
    id: 3,
    name: '3xx - xx',
  }
];

const arr3 = [
  {
    id: 3,
    name: '3xx - xx',
    children: [
      {
        id: 4,
        name: '4xx - xx'
      }
    ]
  }
];

方法封装

function mergeTree(treeList: any[]) {
  const newtree: any[] = [];
  if (!treeList?.length) return treeList;
  // 循环当前树
  treeList.forEach((element) => {
    const newItem = newtree.find(item => item.id === element.id);
    if (newItem) {
      // 如果当前项已经存在,那么当前项就不需要在push,需要将children数据进行合并 并去重
      if (element.children) newItem.children = mergeTree([...(newItem?.children || []), ...element.children])
    } else {
      // 如果当前项不存在,将当前项push进新的数组
      newtree.push({ ...element });
    };
  });

  return newtree;
};

测试验证

const s = mergeTree([...arr1, ...arr2, ...arr3]);
console.log(s);
// 打印结果
// [
//   {
//     id: 1,
//     name: '1xx-xx',
//     children: [
//       {
//         id: 2,
//         name: '2xx-xx'
//       },
//       {
//       id: 5,
//        name: '5xx-xx',
//        children: [
//          {
//            id: 6,
//            name: '6xx-xx'
//          }
//        ]
//      }
//     ]
//   },
//   {
//     id: 3,
//     name: '3xx - xx',
//     children: [
//       {
//         id: 4,
//         name: '4xx - xx'
//       }
//     ]
//   }
// ];
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值