user1937021 user1937021 - 2 months ago 8
jQuery Question

filter by inner value in object

I have the following filter in Jquery, which filters data in a object when the user enters a value in an input field, which works fine, however I want to add another filter which checks if the user input matches any Sellers names within the object eg. for country I have

(val.country.search(regex) != -1)
but how would I add one for sellers name as it doesn't have a key name.

Object:

{
"28": {
"name": "Alex",
"country": "Spain",
"antiquity": "new client",
"amount": "2690.58 USD",
"sellers": {
"Bob": "2690.58 USD",
"Harold": "2690.58 USD"
}
},
"29": {
"name": "Bill",
"country": "UK",
"antiquity": "new client",
"amount": "2690.58 USD",
"sellers": {
"Support": "2690.58 USD",
"admin": "2690.58 USD"
}
},
"30": {
"name": "Jeff",
"country": "USA",
"antiquity": "new client",
"amount": "2690.58 USD",
"sellers": {
"tom": "2690.58 USD",
"harry": "2690.58 USD"
}
}
}


JQuery:

var regex = new RegExp(searchField, "i");
var searchField = $('#search').val();
var regex = new RegExp(searchField, "i");
var output;
var count = 1;

$.each(response, function(key, val){
if ((val.name.search(regex) != -1) || (val.country.search(regex) != -1) || (val.antiquity.search(regex) != -1)){
....
}
});

Answer

Well, you know that the key is sellers - so based off that, you can get the keys (names) of sellers and run your regex check:

$.each(response, function(key, val){
      if ((val.name.search(regex) != -1) || (val.country.search(regex) != -1) || (val.antiquity.search(regex) != -1)){
       ....
      } else if (Object.keys(val.sellers).some(function(seller) { return seller.search(regex) != -1 })) {
          //sellers matches
      }
    });

Array.some will test each array value and return true if any of them match. So Object.keys(val.sellers) will get you the sellers names in an Array, and then test them against your regex. I put it in the else if for readability - it can go in the original if with another || condition.