Angular重构数组字段的解决方法示例

问题

有些数据过多的下拉框数组没法静态定义,只能通过API获取,但API给出的数组字段各式各样,而我弹窗中的下拉框对数组的字段却是固定的,例如:
API给的数据结构是:

{
 id:'',
 text:''
}
复制代码

而我弹窗所需要的固定数据结构为:

{
 type:'',
 value:''
}
复制代码

调用的代码为:

<mat-select *ngSwitchCase="'select'" [formControlName]="form.value" [required]="form.required">
 <mat-option *ngFor="let opt of form.selectArr" [value]="opt.value">
 {{ opt.label ? opt.label : opt.type }}
 </mat-option>
 </mat-select>
复制代码

也就是说,我需要将数组中所有的id修改为value,text修改为type

解决办法

解决思路:我不打算直接去修改原来的数组字段,而采用push的方式。
也就是我设置一个空数组,利用一个foreach循环,使其type=text,value=id,将原来的数据一个一个push进这个空数组,最后循环结束得到的就是我想要的数组了。

sProductCat1List: any[] = [{ type: '', value: '' }]; // 定义数组

this.supplierService.getsProductCat1().subscribe(res => {
 const List = res['data'] || []; // 第一步
 let i = 0; // 第二步
 List.forEach(index => { // 第三步
 this.sProductCat1List[i].type = index.text;
 this.sProductCat1List[i].value = index.id;
 i++;
 this.sProductCat1List.push({ type: '', value: '' });
 });
 });
复制代码

this.supplierService.getsProductCat1()为获取API数组的函数,在此不多做解释。

定义数组:之所以没有设置为any[] = [],是因为空数组无法push进{ type: '', value: '' }第一步:设置一个常量数组,用于获取API的原数组 第二步:设置循环数字(好像也可以不设置,主要是用来检测) 第三步:注意,因为定义的数组{ type: '', value: '' },所以需要先传值,再push,如果你需要一个{ type: '', value: '' }用来作为“不选中”,则可以先push再传值。

作者:再花

%s 个评论

要回复文章请先登录注册