首页 > 解决方案 > 2 在对象中的数组值上选择过滤器

问题描述

我有以下数据对象:

goods = [
    { name: 'Canon', title: 'Canon EOS 5D Mark III Body', tags: ['tag1','tag2','tag3']},
    { name: 'Nikon', title: 'Nikon D3100', tags: ['tag1','tag4','tag5']},
    { name: 'Sony', title: 'Sony CX700', tags: ['tag2','tag3','tag6']},
    { name: 'Fujifilm', title: 'Fujifilm XT20',tags: ['tag1','tag4','tag5']},       
  { name: 'Sony', title: 'Sony CX500', tags: ['tag3','tag4','tag5']},
  { name: 'Nikon', title: 'Nikon D750', tags: ['tag1','tag5','tag6']},
];

还有一个带有 2 个选择框的 html 页面。

<select [(ngModel)]="selectedTag1" (change)="valueSelected1()">
 <option  *ngFor="let item of tagName">{{ item }}</option>
</select>

<select [(ngModel)]="selectedTag2" (change)="valueSelected2()">
 <option  *ngFor="let item of tagName">{{ item }}</option>
</select>

<div *ngFor="let item of goods">
 <app-goods [goodsData]="item"></app-goods>
</div>

在我的 ts 文件中,我想过滤 selectedTag1、selectedTag2 或两者的标签数组。我不知道如何过滤数组(我需要循环遍历它吗?)而且我不知道如何组合这 2 个过滤器(我需要来自 RXJS 的 combineLatest 吗?)。到目前为止我有以下

  ngOnInit() {
   this.tagName = this.dropdownService.brandName;
   this.goods = this.goodsService.goods;
  };

  public valueSelected1() {
   this.goods = this.goodsService.goods.filter(item => item.tags[0] === this.selectedTag1);
   console.log(this.selectedTag1);
  }
  public valueSelected2() {
   this.goods = this.goodsService.goods.filter(item => item.tags[0] === this.selectedTag1);
   console.log(this.selectedTag2);
  }

我想我需要在这里循环遍历数组,item.tags[0]但不确定最好的方法,然后做一个 combineLatest .. 也许不是?我创建了一个stackBlitz

标签: javascriptangular

解决方案


您可以通过多种方式之一执行此操作:

  1. 带吸气剂
get goodsFiltered(): any[] {
   return this.goods?.filter(({ tags }) => tags.indexOf(this.selectedTag1) !== -1 && tags.indexOf(this.selectedTag2) !== -1) ?? [];
}
  1. 使用自定义管道 (恕我直言的最佳方式)
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'filteredGoods' })
export class FilteredGoodsPipe implements PipeTransform {
  transform(goods: any[], { tag1, tag2 }): any[] {
    return goods.filter(({ tags }) => tags.indexOf(tag1) !== -1 && tags.indexOf(tag2) !== -1);
  }
}
<div *ngFor="let item of goods | filteredGoods: { tag1: selectedTag1, tag2: selectedTag2 }">
 <app-goods [goodsData]="item"></app-goods>
</div>
  1. 直接在您的change事件回调中:
  public valueSelected1() {
   this.goods = this.goods.filter(({ tags }) => tags.indexOf(this.selectedTag1) !== -1 && tags.indexOf(this.selectedTag2) !== -1);
  }
  public valueSelected2() {
   this.goods = this.goods.filter(({ tags }) => tags.indexOf(this.selectedTag1) !== -1 && tags.indexOf(this.selectedTag2) !== -1);
  }

希望这可以帮助 :)

编辑:我不知道事物有什么类型,但如果this.goodsService.goodsObservable,你应该管道过滤器运算符

ngOnInit() {
   this.tagName = this.dropdownService.brandName;
   this.goods = this.goodsService.goods.pipe(
      filter(({ tags }) => tags.indexOf(this.selectedTag1) !== -1 && tags.indexOf(this.selectedTag2) !== -1)
   );
  }

推荐阅读