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.
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.
5 Answers
Reset to default 8use filter and contains bination:
_.filter(itemsArr, function(item, index) {
return _.contains(["red", "blue"], item.color);
})
Use a filter function:
_.filter(itemsArr,function(itm){return itm.color=='red' || itm.color=='blue'})
Can you run _.where twice and concat the two resulting arrays?
tempArr = _.where(itemsArr, {color: "red"}).concat(_.where(itemsArr, {color: "blue"}));
Here is the solution
var itemsArr = [{name:"foo", color:"red"}, {name:"bar", color:"blue"}, {name:"bob", color:"red"}];
var filter = ["red","blue"];
var data = {};
_.each(filter, function (item) {
data[item] = true;
});
var returnData = _.filter(itemsArr, function (item) {
return data[item.color];
});
console.log(returnData)
According to the documentation:
Looks through each value in the list, returning an array of all the values that contain all of the key-value pairs listed in properties.
You can also look at the source code if you'd like. Under the hood, where
uses isMatch
:
_.isMatch = function(object, attrs) {
var keys = _.keys(attrs), length = keys.length;
if (object == null) return !length;
var obj = Object(object);
for (var i = 0; i < length; i++) {
var key = keys[i];
if (attrs[key] !== obj[key] || !(key in obj)) return false;
}
return true;
};
Since you cannot have two identical keys, you cannot do what you would like. I would use filter
, as you suggest.