JS中按对应索引纵向合并两个带键数组的实现方法
按索引合并两个数组的对象元素
你可以用map方法结合对象展开运算符来实现需求,这是最简洁直接的方案:
const array1 = [{Name: '1', Type: 'type1'},{Name: '2', Type: 'type2'}]; const array2 = [{file:'one'},{file:'two'}]; // 核心合并逻辑 const combine = array1.map((item, index) => ({ ...item, ...array2[index] })); console.log(combine); // 输出结果: // [{Name: '1', Type: 'type1', file:'one'},{Name: '2', Type: 'type2', file:'two'}]
逻辑说明
map遍历array1的每个元素,同时获取当前元素的索引index- 用
...展开运算符,把array1当前元素的属性和array2对应索引元素的属性合并到一个新对象中 - 如果两个对象存在重复键,
array2的属性会覆盖array1的(你的示例中无重复键,无需担心冲突)
边界情况处理
如果两个数组长度不一致,可以通过以下方式避免报错:
// 合并时自动忽略超出短数组长度的元素 const minLength = Math.min(array1.length, array2.length); const combine = []; for (let i = 0; i < minLength; i++) { combine.push({...array1[i], ...array2[i]}); } // 或者给缺失的索引补空对象,保留长数组的所有元素 const combine = array1.map((item, index) => ({ ...item, ...(array2[index] || {}) }));
内容的提问来源于stack exchange,提问作者rawrstar
相关产品推荐
相关产品推荐

