javascript - 如何遍历类型化数组?
问题描述
我的应用程序Angular中有以下类模型:
export class IItemsModel {
public description: string;
public itemDetail: IItemDetailModel;
public itemCategories: IItemCategoriesModel[]; // array of IItemCategoriesModel
}
export class IItemCategoriesModel {
public id: string | number;
public description: string;
}
我的控制器:
itemModel: IItemsModel;
selectedCategories: any[] = [];
ngOnInit() {
this.itemModel = new IItemsModel();
this.itemModel.itemCategories = [];
}
onSubmit(form: NgForm) {
// here I format the data
}
在模板中,我有一个多项选择,我在其中填写array
所选类别的 ID。
[25, 38] // selectedCategories
问题,我正在使用ngModel将表单与控制器链接,但是要将预填充的数据发送到 API,我必须将 id 格式化为模型格式,即:
{
...,
itemDetail: 'something',
itemCategories: [
{ id: any Id },
{ id: other Id }
]
}
我尝试在方法中按如下方式格式化数据onSubmit()
:
for(let i=0; i<this.selectedCategories.length; i++) {
this.itemModel.itemCategories[i].id = this.selectedCategories[i];
}
但我得到了错误:
TypeError:无法设置未定义@未定义的属性“id”:未定义
您如何格式化 itemCategories 以便能够正确地将数据发送到 API?
解决方案
用于forEach
迭代而不是for
循环。
this.selectedCategories.forEach(f => {
this.itemModel.itemCategories.push({ id: f, description: '' })
});
由于您的selectedCategories
对象是一个数字数组,因此它没有id
属性。这就是为什么你会出错。
在StackBlitz工作演示。
单击按钮并检查控制台日志。
推荐阅读
- date - 使用 SAS 按组计算日期之间的持续时间
- javascript - 如何将获取的数据作为道具传递给带有反应钩子的组件?
- python - SQLAlchemy:“NoneType”对象没有属性“驱动程序名”
- vba - 使用 VBA MarkAsUnread 函数打开 Outlook 对话而不将其标记为已读
- spartacus-storefront - 在 Spartacus 框架中实现新的 OCC 功能
- applescript - 更改文件名后使用 AppleScript 移动文件不起作用
- php - (PHP) 等待子进程超时退出
- angular - 将 FormArray 设置为 FormGroups 数组
- jquery - 逐月更改时替换html文本
- java - Executor Service 任务在 Spring Boot 应用程序中执行两次