对于自动完成输入,我在输入过程中搜索项目属性。现在我想改进这段代码
filterProjects(value: string) {
return this.projects.filter(
project =>
project.key.toLowerCase().indexOf(value.toLowerCase().trim()) >=
0 ||
project.name.toLowerCase().indexOf(value.toLowerCase().trim()) >=
0 ||
project.description?.toLowerCase().indexOf(value.toLowerCase().trim()) >=
0
);
}
用这个:
filterProjects(value: string) {
return this.projects.filter(project =>
[project.key, project.name, project.description].map(
str => str?.toLowerCase().indexOf(value.toLowerCase().trim()) >= 0
)
);
}
我使用可选链接,因为 description
可以是 null 或 undefined。
但它不起作用,这意味着该函数始终返回未修改的数组。此外,当在一项的描述中找到该值时,数组不会仅过滤到此项。
除了使用诸如 if (str !== undefined)
之类的“旧”检查之外,还有什么解决方案?
最佳答案
map
返回一个 bool 值数组,无论如何它始终为真,因此它不是您要查找的谓词。你需要Array.some (如果你打算针对旧浏览器,也在 lodash/underscore/ramda 中)。让我也稍微调整一下内部谓词:
filterProjects(value: string) {
return this.projects.filter(project =>
[project.key, project.name, project.description].some(str =>
str ? str.toLowerCase().includes(value.toLowerCase().trim()) : false
)
);
}
关于javascript - 在数组映射期间与 toLowerCase 和 indexOf 组合的可选链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62484862/