angular - 打字稿中的条件过滤
问题描述
我正在尝试根据用户从多个下拉列表中的选择来过滤数组。但是,如果用户没有从下拉列表中进行选择,我不想将该下拉列表的值用作过滤器。有没有办法在不写一堆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
}
推荐阅读
- python - 有没有办法检查我的python字典中的一个键是否是大写,如果它附加了一些东西?
- javascript - 为什么 Js 文件下载和它所包含的 ajax 请求之间有长时间的停顿?
- java - 如何在启用分层编译的情况下进行调试?
- powershell - 如何更改 xml 中的 xml:lang 属性值?
- python - 如何根据mysql结果数据在python中使用条件打印数据
- vba - 如果值小于另一个单元格值,则清除 Excel 单元格
- java - 在同一类文件中的第二个@test 方法中使用数据提供程序未成功运行
- python - 使用 Python 将 Excel 数据插入 Postgres
- java - 本机库发出启动进程命令
- r - list.files 函数中的时间模式 (R)