首页 > 解决方案 > 跳过 NULL 并在下拉列表中仅显示唯一值

问题描述

我正在尝试从 Angular 应用程序调用 Web API 并在两个下拉列表中显示结果。我有下面的代码,我试图在下拉列表中只显示唯一值并且没有任何 NULL

 service.get<ShipmentByProject[]>(this.entityUrl).subscribe(x => {this.ShipmentList = x});

  for(let i=0; i< this.ShipmentList.length; i++) {
    if( flags[this.ShipmentList[i].customer_shipto_name]) continue;
    flags[this.ShipmentList[i].customer_shipto_name] = true;
    this.shipTo.push(this.ShipmentList[i].customer_shipto_name);
  }

在此处输入图像描述

在 for 循环中获取唯一值,当我尝试删除 NULL 并将 if 条件更改为

   if( (flags[this.ShipmentList[i].customer_shipto_name] || this.ShipmentList[i].customer_shipto_name)) continue;

对于上面的代码,它不返回任何数据

标签: javascriptangulartypescriptangular7

解决方案


您可以使用以下方法删除 NULL 值:

this.shipTo = this.ShipmentList.filter(_ => _.customer_shipto_name);

然后使用 new Set() 仅获取唯一值:

const uniqueValues = new Set(this.shipTo);

推荐阅读