【问题标题】:Iteration of for loop inside object对象内for循环的迭代
【发布时间】:2020-07-13 08:42:46
【问题描述】:

我正在尝试使用 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},....
]

【问题讨论】:

    标签: javascript angular ecmascript-6


    【解决方案1】:

    在顶部或constructor 内部声明this.myObj = []; 并如下修改您的代码

    for (let j = 0; j < sowing.seedSownDetails.length; j++) {
          this.myObj.push({
            sowSeedInventoryId: sowing.seedSownDetails[j]?.inventoryId,
            quantity: sowing.seedSownDetails[j]?.quantity
          });
        }
    
        this.addComments = {
          sowingId: sowing.sowingId,
          cropId: sowing.cropId,
          seedDetails: this.myObj, // You will get array of objects here as expected
    
          seedSowingDate: sowing.sowingDate,
          comments: form.value.comments,
        };
    
    

    【讨论】:

      【解决方案2】:

      你可以定义一个getter:

      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,
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-02-08
        • 2013-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-11-24
        相关资源
        最近更新 更多