【问题标题】:Dynamically creating an object with an array inside动态创建一个内部包含数组的对象
【发布时间】:2021-08-16 07:15:13
【问题描述】:

我正在尝试动态创建一个 JS 对象,其中包含一个数组,例如这个:

//other values omitted for clarity

  "items": [
    {
      "name": "T-Shirt",
      "unit_amount": {
        "currency_code": "USD",
        "value": "90.00"
      },
      "quantity": "1",
      "category": "PHYSICAL_GOODS"
    },
    {
      "name": "Shoes",
      "unit_amount": {
        "currency_code": "USD",
        "value": "45.00"
      },
      "quantity": "2",
      "category": "PHYSICAL_GOODS"
    }
  ],

我可以使用此代码创建单个值:

var product = {};
product.name = "T-Shirt";
product.quantity = "1";
product.category = "PHYSICAL_GOODS";

var subproduct = {};
subproduct.currency_code = "USD";
subproduct.value = "90.00";
product.unit_amount = subproduct;

var jsonString= JSON.stringify(product);

创建:

 {
      "name": "T-Shirt",
      "unit_amount": {
        "currency_code": "USD",
        "value": "90.00"
      },
      "quantity": "1",
      "category": "PHYSICAL_GOODS"
    }

如何将数组中创建的值相加?我有一个onclick 事件,用于为示例中的任何给定“项目”提供值。为了清楚起见,我事先不知道数组将有多少“项目”。

【问题讨论】:

  • 当您说“我正在尝试动态创建一个对象”时,您的意思是:1. 您想将对象推送到数组或 2. 使用来自的 items 属性创建一个完整的主对象如果它不存在就从头开始?
  • 帮自己一个忙,跳过var及其函数范围,使用letconst,而不是两者都有块范围。
  • 您的问题应该是how to add an object to an array?,您在搜索时会找到更多信息。
  • @ross-u 我的意思是根据第二个代码块创建一个新对象并将其推送到数组中,省略的“主”对象值是静态的,不需要动态创建。

标签: javascript arrays javascript-objects


【解决方案1】:

要将对象添加到数组中,您应该使用数组方法.push()

你可以通过以下方式做到这一点:

// Object which has a property `items`, where we will store product objects
var main = {
  items: []
};

// Create the full product object
var product = {
  name: "T-Shirt";
  quantity: "1";
  category: "PHYSICAL_GOODS";
  unit_amount: {
    currency_code = "USD";
    value = "90.00";
  }
};

// Push the new object to the `items` array
main.items.push(product);

【讨论】:

  • @Esquirish 我了解到您正在使用 onclick 事件侦听器将产品添加到数组中。我不知道你是怎么做的,所以我简化了这个例子。
【解决方案2】:

您走在正确的道路上,只需迭代您的代码并将其放入一个数组中:

var productList = [];

for (var i = 0 ; i < 2; i++) {
  // your code
  var product = {};
  product.name = "T-Shirt";
  product.quantity = "1";
  product.category = "PHYSICAL_GOODS";

  var subproduct = {};
  subproduct.currency_code = "USD";
  subproduct.value = "90.00";
  product.unit_amount = subproduct;

  productList.push(product);
}

var answer = JSON.stringify(productList);
console.log(answer);

【讨论】:

  • 感谢您的洞察力,非常感谢
  • 您不需要为了将项目推送到数组而进行迭代。您应该省略 for 循环。
猜你喜欢
  • 2021-03-09
  • 2018-06-28
  • 2021-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-29
  • 2022-01-18
相关资源
最近更新 更多