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

如何将两个对象数组按对应位置匹配合并生成新对象数组

同索引对象数组合并方案

你需要的是按相同下标位置,合并两个数组对应位置的对象属性,以JavaScript为例可参考以下实现:

基础方案(适用于两个数组长度完全一致的场景)

直接遍历第一个数组,取对应下标位置的第二个数组元素做对象合并即可:

const arr1 = [{player_1: 'adeshina'}, {player_1: 'MindReaper'}];
const arr2 = [{player_2: 'thinkerbull'}, {player_2: 'AfroGamer'}];

const mergedArray = arr1.map((item, idx) => ({
  ...item,
  ...arr2[idx]
}));

输出的mergedArray就是你需要的结果:[{player_1: 'adeshina', player_2: 'thinkerbull'}, {player_1: 'MindReaper', player_2: 'AfroGamer'}]

兼容方案(适用于两个数组长度可能不一致的场景)

如果无法保证两个数组长度完全一致,可以取两个数组的最大长度做遍历,同时给不存在的元素做兜底处理避免报错:

const arr1 = [{player_1: 'adeshina'}, {player_1: 'MindReaper'}];
const arr2 = [{player_2: 'thinkerbull'}, {player_2: 'AfroGamer'}];
const maxLen = Math.max(arr1.length, arr2.length);

const mergedArray = Array.from({ length: maxLen }, (_, idx) => ({
  ...(arr1[idx] || {}),
  ...(arr2[idx] || {})
}));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 18:15:01