如何将两个对象数组按对应位置匹配合并生成新对象数组
同索引对象数组合并方案
你需要的是按相同下标位置,合并两个数组对应位置的对象属性,以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
相关产品推荐
相关产品推荐

