javascript - 对象内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},....
]
解决方案
您可以定义一个吸气剂:
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,
};
推荐阅读
- java - 从方法返回字符
- ios - 在嵌套闭包中声明弱
- vba - 如何删除后端数据库、VBA、Access中的SQL记录
- react-native - 消息仅显示在一侧(屏幕左侧) - react-native-gifted-chat
- unix - 基于第 1 列的第 2 列记录数不匹配
- javascript - JavaScript 内置 find() 函数不适用于 angularjs 1.7
- git - git中的樱桃采摘提交:大文件数据是否重复?
- python - 频率 Seaborn 计数图
- laravel - Laravel - 显示第 N 个子值的父级
- mysql - LocalDate MySQL 持久性返回之前的日期