首页 > 解决方案 > 查找一个术语是否包含在对象数组中的对象值中

问题描述

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。

标签: javascriptarraysobject

解决方案


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)){ 

推荐阅读