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

问题场景

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

实现方法

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

复制代码
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'
//       }
//     ]
//   }
// ];
相关推荐
我是伪码农31 分钟前
Vue 1.26
前端·javascript·vue.js
晚霞的不甘1 小时前
Flutter for OpenHarmony 创意实战:打造一款炫酷的“太空舱”倒计时应用
开发语言·前端·flutter·正则表达式·前端框架·postman
2601_949480061 小时前
Flutter for OpenHarmony音乐播放器App实战:定时关闭实现
javascript·flutter·原型模式
这儿有一堆花2 小时前
CSS 拟真光影设计:从扁平到深度的技术复盘
前端·css
_OP_CHEN2 小时前
【前端开发之CSS】(三)CSS 常用元素属性宝典(上):从字体到文本,手把手教你打造高颜值网页!
前端·css·html·网页开发·文本属性·字体属性·页面美化
你脸上有BUG3 小时前
【工程化】记给ant-design-vue打补丁的示例
前端·javascript·vue.js·补丁·ant-design-vue
晚霞的不甘3 小时前
Flutter for OpenHarmony 进阶实战:打造 60FPS 流畅的物理切水果游戏
javascript·flutter·游戏·云原生·正则表达式
雨季6663 小时前
构建 OpenHarmony 文本高亮关键词标记器:用纯字符串操作实现智能标注
开发语言·javascript·flutter·ui·ecmascript·dart
你这个代码我看不懂3 小时前
Vue子父组件.sync
javascript·vue.js·ecmascript
灰灰勇闯IT4 小时前
Flutter for OpenHarmony:布局组件实战指南
前端·javascript·flutter