javascript - 查找一个术语是否包含在对象数组中的对象值中
问题描述
myApp.filter("patientFilter", function() {
return function(rs, searchTerm) {
var addPatient;
var selectedPatients = [];
for(i=0; i<rs.length; i++) {
addPatient = false;
if(rs[i].firstName == searchTerm) || if(rs[i].lastName == searchTerm{ //WRONG
addPatient = true;
}
if (addUser){
selectedPatients.push(rs[i]);
}
我想查找 searchTerm 是否是 firstName 或 lastName 值的一部分。当然,我在代码中的平等并不能解决问题。有任何想法吗?
我从 api 中的 http get 请求得到 rs[i].firstName, rs[i].lastName。
解决方案
String.prototype.includes()
在字符串上,您可以调用include 方法
这里有一个例子
const str = 'To be, or not to be, that is the question.'
console.log(str.includes('To be')) // true
console.log(str.includes('question')) // true
console.log(str.includes('nonexistent')) // false
console.log(str.includes('To be', 1)) // false
console.log(str.includes('TO BE')) // false
console.log(str.includes('')) // true
所以你可以写
if(rs[i].firstName.includes(searchTerm)) || if(rs[i].lastName.includes(searchTerm)){
推荐阅读
- entity-framework-core - .Include 仅加载包含实体的第一个实例
- mustache - 如何使用 mustache.js 访问 Kibana 警报中的特定日志属性?
- python - 如果字符串包含某些子字符串,则按条件过滤
- ios - 协议中的共享实例属性
- java - 为什么这些 Character 对象不保留特征?
- c# - 如何在不使用 Uno.UI 的情况下从 Xamarin.Forms 应用程序调用 JavaScript?
- javascript - 如何在JS中逐字节读取缓冲区对象
- mongodb - MongoDB:如何正确地将集合从 MongoDB 导出到我的计算机?
- laravel-6 - 使用管理员保护成功登录后没有身份验证值
- java - @value 注释返回一个错误的值