angular 删除可观察对象中的重复项

angular remove duplicates in an observable

在这个 mat-option 中,我尝试显示来自我订阅的可观察对象的数据。

   <mat-option *ngFor="let option of (filteredCustomer | async)?.Items"
   [value]="option" (onSelectionChange)="searchDest($event)">
   {{option.Cityname}} 
   </mat-option>

可观察对象的名称是 filteredCustomer。

现在我正在尝试在垫子选项中显示城市名称。这就是结果。

Los Angeles
Boston
Detroit
Los Angeles
Washington
Los Angeles

如你所见,我有重复项。

是否可以删除重复项(例如 sql 中的不同项)?

我的观察来自这个 ts 文件:

public filterCity() {
 var parameters = new CitySearchParameters(100, 0);
 parameters.City = this.city;    
 this.filteredCustomer = this.customerService.get(parameters);
 if (typeof (this.city) == "object") {
  var curCity: any = this.city;
  this.city = curCity.City;
 }
}

谢谢

Set 对象允许您存储任何类型的唯一值,无论是原始值还是对象引用。

因此您可以转换列表,重复项将被删除。

    let list = [...new Set(this.filteredCustomer)];

另一种使用过滤器的方法

let chars = ['A', 'B', 'A', 'C', 'B'];

let uniqueChars = chars.filter((c, index) => {
    return chars.indexOf(c) === index;
});

console.log(uniqueChars); // results = [ 'A', 'B', 'C' ]

您可以使用 RxJS reduce 运算符来保持您的异步管道正常工作,就像这样,假设您要删除基于 .Cityname 属性

的重复项
public filterCity() {
  var parameters = new CitySearchParameters(100, 0);
  parameters.City = this.city;
  this.filteredCustomer = this.customerService.get(parameters).pipe(
    reduce((list, val) => {
      if (!list.length) return [val]
      const foundIndex = list.findIndex((item) => item.cityname === val.cityname);
      if (foundIndex === -1) {
        list.push(val);
      }

      return list;
    }, [])
  );
  if (typeof(this.city) == "object") {
    var curCity: any = this.city;
    this.city = curCity.City;
  }
}

您可以使用 Array#filterArray#findIndex 来删除数组中的重复项。

// credit: 
private uniqueArray(target: Array<any>, property: any): Array<any> {
  return target.filter((item, index) =>
    index === target.findIndex(t => 
      t[property] === item[property]
    )
  );
}

然后您可以使用 map 运算符“捕获”来自控制器中可观察对象的发射,并在将它们呈现在模板中之前删除重复项

public filterCity() {
  var parameters = new CitySearchParameters(100, 0);
  parameters.City = this.city;
  this.filteredCustomer = this.customerService.get(parameters).pipe(
    map(customer => ({
      ...customer,
      Items: uniqueArray(customer.Items, 'Cityname')  // <-- remove duplicates by `Cityname` property
    }))
  );
  if (typeof (this.city) == "object") {
    var curCity: any = this.city;
    this.city = curCity.City;
  }
}

扩展运算符 ... 用于保留可观察对象发射的其他属性,但 Items 属性 数组除外。它被修改为删除重复项。