Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js - find a value of an object key using regexp?

I get an array of objects that looks like this:

var collection = [
  {
    name: 'hello',
    color: 'blue'
  },
  {
    name: 'world',
    color: 'brown'
  }, .... {thousands more}
];

What would be the proper way to use underscore to find out if any of the objects in the array has a value for the 'name' key equal to some regular expression?

_.contains(collection, '/goodbye/i'); <-- this won't work ->

How to tell it to use the 'name' key for searching?

like image 570
SC28 Avatar asked Dec 06 '25 09:12

SC28


1 Answers

You could do:

filter = function (collection, key, regex) {
    return _.filter(collection, function(obj){ return obj[key].match(regex);});
};
like image 181
phenomnomnominal Avatar answered Dec 08 '25 21:12

phenomnomnominal