首页 > 解决方案 > 打字稿中的条件过滤

问题描述

我正在尝试根据用户从多个下拉列表中的选择来过滤数组。但是,如果用户没有从下拉列表中进行选择,我不想将该下拉列表的值用作过滤器。有没有办法在不写一堆if/else语句的情况下做到这一点?

这就是我所拥有的,但我想知道它是否可以浓缩。

filterOptions() {
      if (this.name != undefined && this.age != undefined) {
        this.filteredOptions = this.Options
          .filter(x => x.name == this.name)
          .filter(x => x.age == this.age);
      } else if (this.name == undefined && this.age != undefined) {
        this.filteredOptions = this.Options
          .filter(x => x.age == this.age);
      } else if (this.name != undefined && this.age == undefined) {
        this.filteredOptions = this.Options
          .filter(x => x.flcaLoan == this.name);
      } else {
        this.filteredOptions = this.Options;
      }
  }

标签: angulartypescript

解决方案


您可以将其放在一个过滤器中,如下所示:

this.Options.filter(x => {
  if (this.name && this.name != x.name) {
    return false; // remove if name is set and name doesn't match
  } else if (this.age && this.age != x.age) {
    return false; // remove if age is set and age doesn't match
  }

  return true; // keep
}

推荐阅读