2

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?

0

1 Answer 1

11

You could do:

filter = function (collection, key, regex) {
    return _.filter(collection, function(obj){ return obj[key].match(regex);});
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.