Question

I want to search two item (name=string and location=json). this search is (one input box and two columns for search). at the moment with this code I can find 'name' but i need I need to find location also.

if(textToCheck !== '') {                                
            if((searchArray[i]['location']).toLowerCase().search(textToCheck) === -1) {
                display = false;
            }
        }   

the code that I suggest and doesn't work is:

if(textToCheck !== '') {                                
            if((searchArray[i]['name']).toLowerCase().search(textToCheck) === -1 || (searchArray[i]['location']).toLowerCase().search(textToCheck) === -1) {
                display = false;
            }
        }   

error is :

Uncaught TypeError: Object 123 Street,xxx,xx,Canada,123rd Street,xxx,xx,123 xxx,12345 xxx,France has no method 'toLowerCase' FilterController.showFilteredSet (anonymous function)

Was it helpful?

Solution

As you said location=json, actually searchArray[i]['location'] is a object but not string. You need to do search depend on the what the object like.

Or simply change the object to string format like below:

JSON.stringify(searchArray[i]['location']).toLowerCase().search(textToCheck) === -1

OTHER TIPS

JSON.stringify() is fine. But that searches in the object keys also.

This means:
if your "JSON" object looks like this:

({
  street: 'my street',
  country: 'Texas'
})

JSON.stringify(obj).toLowerCase().search('country') will find a result, even if the "data" doesn't contain it.

instead:
use a generalized way to do a flat search on objects.

Object.prototype.search = function(subject) {
  for(var k in this) {
    if(this.hasOwnProperty(k) && this[k].toString().toLowerCase().search(subject) !== -1) 
      return true;
  }
  return false;
};

var myObj = ({ foo: 'bar', hello: 'world' });
console.log(myObj.search('ar')); //search for "ar", returns true
console.log(myObj.search('ponyo!')); //search for "ponyo!", returns false
console.log(myObj.search('hello')); //search for "hello", returns false

in your case that would decline to:

//somewhere above, run this only once:
Object.prototype.search = function(subject) {
  for(var k in this) {
    if(this[k].toString().toLowerCase().search(subject) !== -1) 
      return true;
  }
  return false;
};
/////


if(textToCheck !== '') {                                
   if((searchArray[i]['name']).toLowerCase().search(textToCheck) === -1 && 
      (searchArray[i]['location']).search(textToCheck) === false) {
         display = false;
   }
}

please be warned that this code modifies the Object prototype, adding a "search" function to all objects (this might conflict with other libraries, you may or may not be using, that want to do the same).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top