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

如何合并两个数字索引对象,实现元素追加式同结构新对象?

问题:如何将数字索引对象的元素追加为新索引项?

我有两个数字索引对象:

let obj = {
    0: {
        "name": "Sasha",
        "age": 20
    },
    1: {
        "name": "Martha",
        "age": 30
    }
}
let obj2 = {
    0: {
        "name": "Stones",
        "age": 89
    }
}

希望生成的新对象将第二个对象的元素作为新索引项追加,预期结果如下:

new_obj = {
    0: {
        "name": "Sasha",
        "age": 20
    },
    1: {
        "name": "Martha",
        "age": 30
    },
    2: {
        "name": "Stones",
        "age": 89
    }
}

我尝试使用扩展运算符和Object.assign()方法,但均无法得到预期结果:

const new_obj = {
    ...obj,
    ...obj2
} // 无法得到预期结果

const new_obj = Object.assign({}, obj, obj2) // 无法得到预期结果

请问是否可以使用这两种方法实现需求?如果可以,具体该如何操作?


解答

为什么原有方法失败?

扩展运算符和Object.assign()的核心逻辑是键冲突时覆盖:当合并的对象存在相同键名(这里两个对象都有键0),后面对象的键值会覆盖前面的。所以直接合并会替换原有元素,而非追加新索引。

可以用这两种方法实现,只需先调整obj2的索引

核心思路是:先计算obj的当前元素个数(即新元素的起始索引),将obj2的元素映射到这些新索引上,再执行合并。

1. 使用扩展运算符

如果obj2只有单个元素:

const newIndex = Object.keys(obj).length;
const new_obj = {
  ...obj,
  [newIndex]: obj2[0]
};

如果obj2包含多个元素,遍历所有元素分配新索引:

let currentIndex = Object.keys(obj).length;
const adjustedObj2 = {};
Object.values(obj2).forEach(item => {
  adjustedObj2[currentIndex++] = item;
});
const new_obj = { ...obj, ...adjustedObj2 };

2. 使用Object.assign()

单个元素的场景:

const newIndex = Object.keys(obj).length;
const new_obj = Object.assign({}, obj, { [newIndex]: obj2[0] });

多个元素的场景:

let currentIndex = Object.keys(obj).length;
const adjustedObj2 = {};
Object.values(obj2).forEach(item => {
  adjustedObj2[currentIndex++] = item;
});
const new_obj = Object.assign({}, obj, adjustedObj2);

补充说明

如果你的场景更接近数组(数字索引、连续递增),直接使用数组会更省心:

const arr1 = Object.values(obj);
const arr2 = Object.values(obj2);
const newArr = [...arr1, ...arr2];
// 若需要转回对象,可按需转换
const new_obj = Object.fromEntries(newArr.map((item, idx) => [idx, item]));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 19:05:32