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

问题场景

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

实现方法

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

复制代码
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'
//       }
//     ]
//   }
// ];
相关推荐
Yvonne爱编码23 分钟前
CSS- 2.1 实战之图文混排、表格、表单
前端·css·html·github·状态模式·html5·hbuilder
前端小巷子26 分钟前
CSS面试题汇总
前端·css·面试
绝美焦栖33 分钟前
vue复杂数据类型多层嵌套的监听
前端·javascript·vue.js
GoodStudyAndDayDayUp38 分钟前
gitlab+portainer 实现Ruoyi Vue后端CI/CD
vue.js·ci/cd·gitlab
xixixin_2 小时前
【Vite】前端开发服务器的配置
服务器·前端·网络
.生产的驴2 小时前
Vue3 加快页面加载速度 使用CDN外部库的加载 提升页面打开速度 服务器分发
运维·服务器·前端·vue.js·分布式·前端框架·vue
史迪仔01122 小时前
Python生成器:高效处理大数据的秘密武器
前端·数据库·python
蓝婷儿3 小时前
前端面试每日三题 - Day 34
前端·面试·职场和发展
CopyLower3 小时前
苹果计划将AI搜索集成至Safari:谷歌搜索下降引发的市场变革
前端·人工智能·safari
我是Superman丶5 小时前
【技巧】前端VUE用中文方法名调用没效果的问题
前端·javascript·vue.js