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

问题场景

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

实现方法

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

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'
//       }
//     ]
//   }
// ];
相关推荐
JUNAI_Strive_ving6 分钟前
番茄小说逆向爬取
javascript·python
看到请催我学习15 分钟前
如何实现两个标签页之间的通信
javascript·css·typescript·node.js·html5
twins352035 分钟前
解决Vue应用中遇到路由刷新后出现 404 错误
前端·javascript·vue.js
qiyi.sky1 小时前
JavaWeb——Vue组件库Element(3/6):常见组件:Dialog对话框、Form表单(介绍、使用、实际效果)
前端·javascript·vue.js
煸橙干儿~~1 小时前
分析JS Crash(进程崩溃)
java·前端·javascript
哪 吒1 小时前
华为OD机试 - 几何平均值最大子数(Python/JS/C/C++ 2024 E卷 200分)
javascript·python·华为od
安冬的码畜日常1 小时前
【D3.js in Action 3 精译_027】3.4 让 D3 数据适应屏幕(下)—— D3 分段比例尺的用法
前端·javascript·信息可视化·数据可视化·d3.js·d3比例尺·分段比例尺
杨荧1 小时前
【JAVA开源】基于Vue和SpringBoot的洗衣店订单管理系统
java·开发语言·vue.js·spring boot·spring cloud·开源
l1x1n02 小时前
No.3 笔记 | Web安全基础:Web1.0 - 3.0 发展史
前端·http·html
Q_w77422 小时前
一个真实可用的登录界面!
javascript·mysql·php·html5·网站登录