我正在尝试使用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},....
]
答案 0 :(得分:1)
您可以定义吸气剂:
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,
};
答案 1 :(得分:1)
在this.myObj = [];
顶部或内部声明constructor
,并如下所示修改代码
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,
};