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

问题场景

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

实现方法

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

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'
//       }
//     ]
//   }
// ];
相关推荐
午后书香8 分钟前
一天三场面试,口干舌燥要晕倒(二)
前端·javascript·面试
Book_熬夜!24 分钟前
CSS—补充:CSS计数器、单位、@media媒体查询
前端·css·html·媒体
程序员大澈24 分钟前
1个基于 Three.js 的 Vue3 组件库
javascript·vue.js
程序员大澈30 分钟前
3个 Vue Scoped 的核心原理
javascript·vue.js
hyyyyy!34 分钟前
《原型链的故事:JavaScript 对象模型的秘密》
javascript·原型模式
计算机学姐41 分钟前
基于Asp.net的教学管理系统
vue.js·windows·后端·sqlserver·c#·asp.net·visual studio
程序员大澈43 分钟前
3个好玩且免费的api接口
javascript·vue.js
程序员大澈1 小时前
4个 Vue 路由实现的过程
javascript·vue.js·uni-app
几度泥的菜花1 小时前
如何禁用移动端页面的多点触控和手势缩放
前端·javascript
狼性书生1 小时前
electron + vue3 + vite 渲染进程到主进程的双向通信
前端·javascript·electron