I'm trying to filter an array based on user selection from multiple drop downs. However, if a user does not make a selection from a drop down I do not want to use that drop down's value as a filter. Is there a way to do this without writing a bunch of if/else
statements?
This is what I have but I'm wondering if it can be condensed.
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;
}
}
答案 0 :(得分:2)
You can just put it in one filter, like so:
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
}