javascript 下划线 where 过滤器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32851445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Underscore where filter
提问by Croftc
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:
我正在尝试使用 Underscorewhere
来过滤一组对象,但我似乎无法弄清楚如何让它过滤同一键的多个值。例如:
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
我试图让它从所有带有颜色的red
项目和所有带有颜色的项目中返回一个数组blue
......这可能吗?我试过了
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.
但这没有用。如果我必须只使用_.filter
并写出我自己的谓词,我会,但我只是想知道是否有人尝试这样做并找到了解决方案。
回答by Praveen Prasannan
回答by Phil C
回答by Jeremy Schultz
Can you run _.where twice and concat the two resulting arrays?
你能运行 _.where 两次并连接两个结果数组吗?
tempArr = _.where(itemsArr, {color: "red"}).concat(_.where(itemsArr, {color: "blue"}));
回答by Rubel hasan
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)
回答by gwg
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 pairslisted in properties.
查看列表中的每个值,返回包含属性中列出的所有键值对的所有值的数组。
You can also look at the source codeif you'd like. Under the hood, where
uses isMatch
:
如果您愿意,也可以查看源代码。在引擎盖下,where
使用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.
由于您不能拥有两个相同的密钥,因此您无法做自己想做的事。我会filter
按照你的建议使用。