If the object contains any substring in the array

I have this set of keywords:

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

And such an object:

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

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

Update

Here is what I ended up using. Thanks everyone!

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

+3
source share
5 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

It is case sensitive and does not take word boundaries into account.


2nd answer

Here the method is insensitive , and - .

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 keywordscontains characters that have special meaning in RegExp, they must be escaped.

+4
source

If it personcontains only 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);
      }
    });
  }
}

, , .

+3

, , indexOf. indexOf , , IE < 9, MDN.

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/

+1
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;
}
0

- .contains(str) String Array:

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;
    };
}

.js, , :

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
0

All Articles