You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用reduce或forEach合并长度不同的对象数组?

解决方案:用forEach或reduce合并两个键名不同的对象数组

当然可以!不管是forEach还是reduce都能轻松搞定这个需求,我给你分别整理了两种方案的代码和思路:

方法一:使用forEach(直观易懂,可修改原数组)

forEach的思路很直接:遍历第一个数组的每个元素,根据当前索引从第二个数组取出对应对象,再把两者的属性合并到一起。

// 你的原始数组
const links = [ { name: 'JRD', status: 'active' }, { name: 'JRM', status: 'active' }, { name: 'JRH', status: 'active' } ];
const colors = [ { color: 'red', value: '#f00' }, { color: 'green', value: '#0f0' }, { color: 'blue', value: '#00f' }, { color: 'cyan', value: '#0ff' }, { color: 'magenta', value: '#f0f' }, { color: 'yellow', value: '#ff0' }, ];

// 用forEach合并
links.forEach((link, index) => {
  // 用Object.assign合并对象,加`colors[index] || {}`避免links长度超过colors时报错
  Object.assign(link, colors[index] || {});
});

console.log(links); // 输出你想要的合并结果

小提示:如果不想修改原数组,也可以用展开运算符创建新对象,比如const newLink = {...link, ...(colors[index] || {})},再把新对象存入新数组即可。

方法二:使用reduce(函数式风格,不修改原数组)

如果你希望保留原数组的完整性,reduce是更合适的选择——它会返回一个全新的合并后数组,完全不影响原始数据。

// 你的原始数组
const links = [ { name: 'JRD', status: 'active' }, { name: 'JRM', status: 'active' }, { name: 'JRH', status: 'active' } ];
const colors = [ { color: 'red', value: '#f00' }, { color: 'green', value: '#0f0' }, { color: 'blue', value: '#00f' }, { color: 'cyan', value: '#0ff' }, { color: 'magenta', value: '#f0f' }, { color: 'yellow', value: '#ff0' }, ];

// 用reduce合并,返回新数组
const mergedArray = links.reduce((acc, link, index) => {
  // 合并当前link和对应color的属性,加入累积数组
  acc.push({ ...link, ...(colors[index] || {}) });
  return acc;
}, []); // 初始值设为空数组

console.log(mergedArray); // 输出期望的合并结果

解释:reduce的回调函数里,acc是用来存储结果的累积数组,每一步我们都创建一个包含link和对应color属性的新对象,再把它加入acc,最后返回完整的累积数组。

两种方法都能实现你的需求,选哪种全看你是否需要保留原数组~

内容的提问来源于stack exchange,提问作者arunmmanoharan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:44:43