首页 > 解决方案 > 对象内for循环的迭代

问题描述

我正在尝试使用 for 循环迭代我的数组并且它运行良好,现在如果我希望它在一个对象内迭代它,我该怎么做?

下面是我的代码

for (let j = 0; j < sowing.seedSownDetails.length; j++) {
  this.myObj = {
    sowSeedInventoryId: sowing.seedSownDetails[j]?.inventoryId,
    quantity: sowing.seedSownDetails[j]?.quantity
  };
  console.log(this.myObj); //all the iterations work here
}

this.addComments = {
  sowingId: sowing.sowingId,
  cropId: sowing.cropId,
  seedDetails: [this.myObj], // i want all my iteration object inside this array

  seedSowingDate: sowing.sowingDate,
  comments: form.value.comments
};

预期输出:

seedDetails: [
{object1},
{object2},....
]

标签: javascriptangularecmascript-6

解决方案


您可以定义一个吸气剂:

private get myObj() {
   for (let j = 0; j < this.sowing.seedSownDetails.length; j++) {
      const myObj = {
        sowSeedInventoryId: this.sowing.seedSownDetails[j]?.inventoryId,
        quantity: this.sowing.seedSownDetails[j]?.quantity
      };
    }

    return myObj;
}

并像这样消费它:

this.addComments = {
   sowingId: sowing.sowingId,
   cropId: sowing.cropId,
   seedDetails: this.myObj, // consume here

   seedSowingDate: sowing.sowingDate,
   comments: form.value.comments,
};

推荐阅读