Angular typescript中的条件过滤
我正在尝试根据用户从多个下拉列表中的选择筛选数组。但是,如果用户没有从下拉列表中进行选择,我不想使用该下拉列表的值作为过滤器。有没有一种方法可以在不编写一堆Angular typescript中的条件过滤,angular,typescript,Angular,Typescript,我正在尝试根据用户从多个下拉列表中的选择筛选数组。但是,如果用户没有从下拉列表中进行选择,我不想使用该下拉列表的值作为过滤器。有没有一种方法可以在不编写一堆if/else语句的情况下做到这一点 这是我有的,但我想知道它是否可以浓缩 filterOptions() { if (this.name != undefined && this.age != undefined) { this.filteredOptions = this.Options
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;
}
}
您可以将其放在一个过滤器中,如下所示:
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
}