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

如何将两个数组对象合并到同一数组的相同索引位置?

按索引合并两个数组中的对象

要将两个数组中同一索引位置的对象合并为单个对象,最终生成合并后的数组,有几种简洁的实现方式:

方法1:使用map + 对象展开运算符(最简洁)

针对两个数组长度相同的场景(如你的示例),可以直接用Array.map()遍历数组,结合对象展开运算符...合并对应索引的对象:

let a = [{name: 'asha', age:20, mother: "sushi", father: "Nick"}];
let b = [{class: "10th", Sub: "science", Marks: 30}];

const mergedArray = a.map((obj, index) => ({
  ...obj,
  ...b[index]
}));

console.log(mergedArray);
// 输出:[{name: 'asha', age:20, mother: "sushi", father: "Nick", class: "10th", Sub: "science", Marks: 30}]

方法2:处理数组长度不一致的情况

如果两个数组长度不同,想要以较长数组的长度为基准合并(缺失索引的对象用空对象兜底),可以用Array.from():

let a = [{name: 'asha', age:20}, {name: 'bob', age:22}];
let b = [{class: "10th"}, {class: "11th"}, {class: "12th"}];

const mergedArray = Array.from(
  { length: Math.max(a.length, b.length) },
  (_, index) => ({
    ...(a[index] || {}),
    ...(b[index] || {})
  })
);

console.log(mergedArray);
// 输出:[
//   {name: 'asha', age:20, class: "10th"},
//   {name: 'bob', age:22, class: "11th"},
//   {class: "12th"}
// ]

方法3:使用Object.assign()替代展开运算符

如果更习惯ES5的写法,可以用Object.assign()实现相同的合并逻辑:

const mergedArray = a.map((obj, index) => Object.assign({}, obj, b[index]));

注意点

  • 如果两个对象存在同名属性,后面的对象(b[index])的属性值会覆盖前面的(a[index]),若要保留a的属性,调整顺序即可(把...b[index]放在...obj前面)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 11:40:14