如何去除API返回数据中下拉菜单的重复CountryCode值?
解决Angular下拉菜单重复CountryCode的问题
方法一:在数据获取时直接处理去重
在TypeScript中,从API拿到数据后,提取所有CountryCode并利用Set自动去重的特性生成唯一列表:
- 在组件类中定义存储唯一国家代码的变量:
uniqueCountryCodes: string[] = [];
- 修改
ngOnInit中的订阅逻辑,处理数据去重:
ngOnInit(){ this.dataService.getUserDetail().subscribe(details => { this.detail = details; // 提取所有CountryCode并去重 const allCodes = details.map(item => item.CountryCode); this.uniqueCountryCodes = [...new Set(allCodes)]; }); }
- 修改HTML模板,遍历去重后的列表:
<div class="col "> <label for="country" class="control-label" required>Country:</label><br> <select required="" class="form-control" [(ngModel)]="detailM" formControlName="PropertyCountryCode"> <option [ngValue]="null"></option> <option *ngFor="let code of uniqueCountryCodes">{{code}}</option> </select> <button (click)="filterCountry()">button</button> </div>
方法二:使用自定义管道实现复用
如果多个组件都需要类似的去重需求,可以创建一个自定义管道:
- 终端执行命令生成管道文件:
ng generate pipe unique
- 修改
unique.pipe.ts的逻辑,根据指定字段去重:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'unique' }) export class UniquePipe implements PipeTransform { transform(value: any[], key: string): any[] { if (!value || !key) return value; // 根据指定字段提取并去重 return [...new Set(value.map(item => item[key]))]; } }
- 在模板中直接使用管道:
<div class="col "> <label for="country" class="control-label" required>Country:</label><br> <select required="" class="form-control" [(ngModel)]="detailM" formControlName="PropertyCountryCode"> <option [ngValue]="null"></option> <option *ngFor="let code of detail | unique: 'CountryCode'">{{code}}</option> </select> <button (click)="filterCountry()">button</button> </div>
方法三:保留完整对象的去重(如需用到其他属性)
如果后续需要用到国家对象的其他属性,可过滤数组只保留每个CountryCode的第一个实例:
ngOnInit(){ this.dataService.getUserDetail().subscribe(details => { this.detail = details; this.uniqueCountryItems = details.filter((item, index, self) => index === self.findIndex(t => t.CountryCode === item.CountryCode) ); }); }
模板中遍历完整对象:
<option *ngFor="let item of uniqueCountryItems" [ngValue]="item.CountryCode">{{item.CountryCode}}</option>
内容的提问来源于stack exchange,提问作者Swapnali
相关产品推荐
相关产品推荐

