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

如何将两个对象数组合并为对应位置属性融合的新对象数组?

合并两个数组中对应索引的对象属性

你现在有两个对象数组,需要把对应索引的对象属性合并成新数组:

原数组 arr:

const arr =  [
    {
        "id": 0,
        "name": "John",
    },
    {
        "id": 1,
        "name": "Kim",
    },
    {
        "id": 2,
        "name": "Steven",
    },
]

原数组 arr2:

const arr2 = [
    {
        "surname": "Lewis"
    },
    {
        "surname": "Pitt"
    },
    {
        "surname": "Watson"
    }
]

你的错误代码把arr2.map的结果(一个完整数组)直接追加到了arr后面,所以新数组最后多了一个嵌套数组,这不是你要的效果。

正确解法

你需要遍历其中一个数组,对每个索引位置,把arr和arr2对应位置的对象合并。可以用Array.map来实现:

// 方法1:使用对象扩展运算符
const newArr = arr.map((item, index) => ({
    ...item,
    ...arr2[index]
}));

// 方法2:使用Object.assign
const newArr = arr.map((item, index) => Object.assign({}, item, arr2[index]));

两种方法都能得到你想要的结果:

newArr =  [
    {
        "id": 0,
        "name": "John",
        "surname": "Lewis",
    },
    {
        "id": 1,
        "name": "Kim",
        "surname": "Pitt"
    },
    {
        "id": 2,
        "name": "Steven",
        "surname": "Watson"
    },
]

注意事项

  • 确保两个数组长度一致,否则索引越界的位置会得到undefined,合并后属性会缺失。
  • 如果两个对象有同名属性,后面的对象(这里是arr2[index])的属性会覆盖前面的(item)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:15:42