javascript 如何使用 underscore.js 库中的 _.where 方法进行更详细的搜索
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20888621/
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
How to use _.where method from underscore.js library for more elaborated searchs
提问by Lothre1
var a = {
"title": "Test 1",
"likes": {
"id": 1
}
}
var b = {
"title": "Test 2",
"likes": {
"id": 2
}
}
var c = [a, b];
var d = _.where(c, {
"title": "Test 2",
"likes": {
"id": 2
}
});
//d => outputs an empty array []
In this situation i would expect to get the reference to object in memory but d but actually it just works on root properties.
在这种情况下,我希望在内存中获得对对象的引用,但 d 但实际上它只适用于根属性。
_.where(c, {title: "Test 2"});
=> outputs [object]
where object is the reference for c[1];
其中 object 是 c[1] 的引用;
EDIT:found a possible solution using _.filter()
编辑:使用 _.filter() 找到了一个可能的解决方案
_.filter( c, function(item){
if (item.title == "Test 1" && item.likes.id == 1){
return item;
}
})
outputs => [object] with reference for variable a
回答by mu is too short
_.filter
is the right way to do this, _.where
is just a _.filter
shortcut for filtering on simple key/value pairs. You can see this from the source:
_.filter
是正确的方法,_.where
只是_.filter
过滤简单键/值对的快捷方式。您可以从源中看到这一点:
// Convenience version of a common use case of `filter`: selecting only objects
// containing specific `key:value` pairs.
_.where = function(obj, attrs, first) {
if (_.isEmpty(attrs)) return first ? void 0 : [];
return _[first ? 'find' : 'filter'](obj, function(value) {
for (var key in attrs) {
if (attrs[key] !== value[key]) return false;
}
return true;
});
};
The docs could be a little more explicit but at least the comment in the source is clear.
文档可能更明确一些,但至少源代码中的注释是清楚的。