Croftc Croftc - 1 year ago 122
Javascript Question

Underscore where filter

I'm trying to use Underscore's "where" to filter an array of objects, but I can't seem to figure out how to get it to filter multiple values for the same key. For example:

var itemsArr = [{name:"foo", color:"red"}, {name:"bar", color:"blue"}, {name:"bob", color:"yellow"}];

I'm trying to get it to return an array off all items with color "red" AND all items with color "blue"... Is this possible? I've tried

tempArr = _.where(itemsArr, {color:["red", "blue"]});

but that didn't work. If I have to just use _.filter and write out my own predicate I will, but I was just wondering if anyone else had tried to do this and found a solution. Thanks

Answer Source

use filter and contains combination:

_.filter(itemsArr, function(item, index) {
  return _.contains(["red", "blue"], item.color);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download