#angular #typescript
#angular #typescript
Вопрос:
Я пытаюсь отфильтровать массив на основе выбора пользователя из нескольких выпадающих списков. Однако, если пользователь не делает выбор из выпадающего списка, я не хочу использовать значение этого выпадающего списка в качестве фильтра. Есть ли способ сделать это, не написав кучу if/else
инструкций?
Это то, что у меня есть, но мне интересно, можно ли его сжать.
filterOptions() {
if (this.name != undefined amp;amp; this.age != undefined) {
this.filteredOptions = this.Options
.filter(x => x.name == this.name)
.filter(x => x.age == this.age);
} else if (this.name == undefined amp;amp; this.age != undefined) {
this.filteredOptions = this.Options
.filter(x => x.age == this.age);
} else if (this.name != undefined amp;amp; this.age == undefined) {
this.filteredOptions = this.Options
.filter(x => x.flcaLoan == this.name);
} else {
this.filteredOptions = this.Options;
}
}
Ответ №1:
Вы можете просто поместить его в один фильтр, например:
this.Options.filter(x => {
if (this.name amp;amp; this.name != x.name) {
return false; // remove if name is set and name doesn't match
} else if (this.age amp;amp; this.age != x.age) {
return false; // remove if age is set and age doesn't match
}
return true; // keep
}