Lot*_*re1 9 javascript underscore.js
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 []
Run Code Online (Sandbox Code Playgroud)
在这种情况下,我希望在内存中获得对象的引用,但实际上它只适用于根属性.
_.where(c, {title: "Test 2"});
=> outputs [object]
Run Code Online (Sandbox Code Playgroud)
其中object是c [1]的引用;
编辑: 使用_.filter()找到了一个可能的解决方案
_.filter( c, function(item){
if (item.title == "Test 1" && item.likes.id == 1){
return item;
}
})
outputs => [object] with reference for variable a
Run Code Online (Sandbox Code Playgroud)
mu *_*ort 12
_.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;
});
};
Run Code Online (Sandbox Code Playgroud)
文档可能更明确一些,但至少来源中的评论是明确的.
| 归档时间: |
|
| 查看次数: |
19098 次 |
| 最近记录: |