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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With