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

如何将对象正确添加到JavaScript数组,避免额外外层键名

如何正确将对象添加到数组以得到预期结构

你当前代码的问题在于使用{product1}这种写法——这是ES6的对象字面量简写语法,会创建一个以变量名为键、变量值为对应值的新对象,所以才会出现{"product1": {...}}这种多余的嵌套结构,而不是直接把product对象本身加入数组。

下面是几种正确的实现方式:

方法1:使用扩展运算符直接添加对象

去掉包裹对象的大括号,直接把product变量放入扩展后的数组中:

const aggregator = [];

const product1 = {"id": "prod1", "contents": {"key1": "value1"}};
const product2 = {"id": "prod2", "contents": {"key2": "value2"}};

aggregator = [...aggregator, product1];
aggregator = [...aggregator, product2];

方法2:使用数组push方法(更简洁高效)

如果允许直接操作原数组,push是最直接的方式:

const aggregator = [];

const product1 = {"id": "prod1", "contents": {"key1": "value1"}};
const product2 = {"id": "prod2", "contents": {"key2": "value2"}};

aggregator.push(product1);
aggregator.push(product2);

方法3:一次性初始化目标数组

如果不需要逐步添加对象,也可以直接创建包含目标元素的数组:

const product1 = {"id": "prod1", "contents": {"key1": "value1"}};
const product2 = {"id": "prod2", "contents": {"key2": "value2"}};

const aggregator = [product1, product2];

验证结果

执行任意一种方法后,打印JSON.stringify({ aggregator }, null, 2),会得到你预期的结构:

{
  "aggregator": [
    {
      "id": "prod1",
      "contents": {
        "key1": "value1"
      }
    },
    {
      "id": "prod2",
      "contents": {
        "key2": "value2"
      }
    }
  ]
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 13:36:32