当前位置: 首页 > news >正文

在 Vue 3 中将拆分后的数组合并回原数组

接上文Vue 3 中按照某个字段将数组分成多个数组_vue3怎么进行数组对象--分割对象-CSDN博客

方法一:使用 flat() 方法

// 假设这是拆分后的多维数组
const splitArrays = [[{id: 1, category: 'A'}, {id: 3, category: 'A'}],[{id: 2, category: 'B'}, {id: 5, category: 'B'}],[{id: 4, category: 'C'}]
];// 使用 flat() 合并
const mergedArray = splitArrays.flat();
console.log(mergedArray);

方法二:使用 reduce() 方法

const mergedArray = splitArrays.reduce((acc, currentArray) => {return acc.concat(currentArray);
}, []);

方法三:使用展开运算符

const mergedArray = [].concat(...splitArrays);

方法四:如果拆分后是对象形式,转换为数组再合并

// 假设拆分后是这样的对象
const groupedByCategory = {A: [{id: 1, category: 'A'}, {id: 3, category: 'A'}],B: [{id: 2, category: 'B'}, {id: 5, category: 'B'}],C: [{id: 4, category: 'C'}]
};// 合并方法
const mergedArray = Object.values(groupedByCategory).flat();

方法五:在 Vue 3 组件中使用计算属性

import { computed } from 'vue';export default {setup() {const splitArrays = [[{id: 1, category: 'A'}, {id: 3, category: 'A'}],[{id: 2, category: 'B'}, {id: 5, category: 'B'}],[{id: 4, category: 'C'}]];const mergedArray = computed(() => splitArrays.flat());return { mergedArray };}
};

方法六:保持原始顺序的合并

如果需要保持原始数组的顺序,可以在拆分时保留索引信息

// 拆分时保留原始索引
const originalArray = [{id: 1, category: 'A', index: 0},{id: 2, category: 'B', index: 1},{id: 3, category: 'A', index: 2},{id: 4, category: 'C', index: 3},{id: 5, category: 'B', index: 4}
];// 拆分操作
const groupedByCategory = originalArray.reduce((acc, item) => {const key = item.category;if (!acc[key]) {acc[key] = [];}acc[key].push(item);return acc;
}, {});// 合并时按原始索引排序
const mergedArray = Object.values(groupedByCategory).flat().sort((a, b) => a.index - b.index).map(({index, ...rest}) => rest); // 移除临时索引console.log(mergedArray);

注意事项

  1. 如果拆分后的数组结构不是简单的二维数组,可能需要先进行适当处理

  2. 合并后的数组顺序可能与原数组不同,如需保持顺序需要额外处理

  3. 对于大型数组,flat() 方法性能较好

  4. 如果数组中包含对象引用,合并后的数组仍会引用相同的对象

相关文章:

  • 云轴科技ZStack入选中国人工智能产业发展联盟《大模型应用交付供应商名录》
  • Muduo网络库实现 [十六] - HttpServer模块
  • 线上蓝桥杯比赛环境配置
  • C#中扩展方法和钩子机制使用
  • 中间件--ClickHouse-9--MPP架构(分布式计算架构)
  • 51单片机实验六:通用型1602液晶操作方法
  • 使用DeepSeek生成PPT的详细指南
  • Oracle、MySQL、PostgreSQL三大数据库对比分析
  • Python爬虫第16节-动态渲染页面抓取之Selenium使用上篇
  • kubernetes-使用ceph-csi
  • vscode中markdown一些插件用不了解决方式
  • HTML 初识
  • 本地部署ai图片转生成视频,一键运行包的制作教程。
  • AbMole| Lofexidine hydrochloride(CAS号21498-08-8;目录号M3169)
  • 大模型面经 | DeepSpeed中ZeRO-1、ZeRO-2和ZeRO-3的区别是什么?
  • QT常见显示类控件及其属性
  • 学习设计模式《二》——外观模式
  • 快手本地生活2024年GMV同增200%,“新线城市+AI”将成增长引擎
  • LabVIEW油气井井下集成监测系统
  • 492Q 型气缸盖双端面铣削组合铣床总体设计
  • 今年一季度,上海对东盟进出口总值同比增长7.1%
  • 一季度浙江实现生产总值22300亿元,同比增长6.0%
  • 诺奖得主等数十位经济学家发表宣言反对美关税政策
  • 精细喂养、富养宠物,宠物经济掀起新浪潮|私家周历
  • 上海奉贤这所九年一贯制学校将迎首批新生,有何特色?
  • 平安银行一季度净赚超140亿元降5.6%,营收降13.1%