3

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

2
  • Show what you have tried and clarify whether or not you want to handle cases with nested objects string arrays/maps in your searched object. Commented Feb 13, 2014 at 1:41
  • Loop the person object, split the string by words, then loop the keywords array and compare, or use indexOf Commented Feb 13, 2014 at 1:41

5 Answers 5

4
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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer! I wasn't familiar with some.
3

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.

Comments

1

Iterate through each property in the object, then split the property into tokens and check if each token is in the array using indexOf. indexOf will not be available on older browsers, I believe IE < 9, but you can find a shim in the MDN documentation.

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

var person2 = {
    name: 'John',
    quote: 'I love the color orange'
};

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

function contains(obj, keywords){
    for(x in person){
        if(obj.hasOwnProperty(x)){
            var tokens = obj[x].split(/\s/);
            for(var i = 0; i < tokens.length; i++){
                if(keywords.indexOf(tokens[i])!= -1){
                   return true;
                }
            }
        }
    }
    return false;
}

alert(contains(person, keywords));
alert(contains(person2, keywords));

JS Fiddle: http://jsfiddle.net/BaC5p/

3 Comments

Accidental window.x ;)
@Amadan not sure what your referring to?
for(x in person) without var.
0
function testKeyWords(keywords) {
    var keyWordsExp = new RegExp('\b(' + keywords.join(')|(') + ')\b', 'g');
    for(var key in person) {
        if(keyWordsExp.test(person[key])) {
            return true;
        }
    }
    return false;
}

Comments

0

The most comfortable way is to add .contains(str) to the String and to the Array prototype:

if (typeof String.prototype.contains === 'undefined') {
    String.prototype.contains = function (it) {
        return this.indexOf(it) != -1;
    };
}
if (typeof Array.prototype.contains === 'undefined') {
    Array.prototype.contains = function (it) {
        for (var i in this) {
            var elem = this[i].toString();
            if (elem.contains(it)) return true;
        }
        return false;
    };
}

If you put the code above into a .js file which you include, you can use it everywhere in your code like so:

var b = ["A Bell", "A Book", "A Candle"];

var result1 = b.contains("Book"); // returns: true, it is contained in "A Book"
var result2 = b.contains("Books"); // returns: false, it is not contained

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.