Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If object contains any substring in an array

I've got an array of keywords like this:

var keywords = ['red', 'blue', 'green'];

And an object like this:

var person = {
    name: 'John',
    quote: 'I love the color blue'
};

How would I determine if any value in the person object contains any of the keywords?

Update

This is what I ended up using. Thanks to everyone!

http://jsbin.com/weyal/10/edit?js,console

like image 613
matthoiland Avatar asked Dec 05 '25 16:12

matthoiland


2 Answers

function isSubstring(w){
  for(var k in person) if(person[k].indexOf(w)!=-1) return true;
  return false
}

keywords.some(isSubstring) // true if a value contains a keyword, else false

This is case-sensitive and does not respect word boundaries.


2nd Answer

Here's a way that is case-insensitive, and does respect word boundaries.

var regex = new RegExp('\\b('+keywords.join('|')+')\\b','i');
function anyValueMatches( o, r ) {
  for( var k in o ) if( r.test(o[k]) ) return true;
  return false;
}

anyValueMatches(person,regex) // true if a value contains a keyword, else false

If any keywords contain characters that have special meaning in a RegExp, they would have to be escaped.

like image 186
Matt Avatar answered Dec 07 '25 04:12

Matt


If person only contains strings, this should do it:

for (var attr in person) {
  if (person.hasOwnProperty(attr)) {
    keywords.forEach(function(keyword) {
      if (person[attr].indexOf(keyword) !== -1) {
        console.log("Found " + keyword + " in " + attr);
      }
    });
  }
}

If you want deep search, then you need a function that recurses on objects.

like image 29
Amadan Avatar answered Dec 07 '25 06:12

Amadan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!