我基本上都是尝试用这个问题做的,但是使用数组并使用相应数组的值返回所有对象,而不仅仅是值: Filter backbone collection by attribute value
我的本能是在人物收藏中使用_.filter或_.partition,但我们对如何比较它们感到困惑。返回并没有得到预期的结果。
使用以下命令,通过路由器传递id:
friendsRoute: function(id){
persons = new App.Collections.Persons();
persons.fetch().done(function(){
var single = persons.find(function(i){
return i.get('id') == id;
});
var friendsIds = single.get('friends');
var friends = ?
//var friendsList = new App.Views.FriendsList();
//friendsList.render({ friends: friends });
});
},
我有一个friendsIds数组(Joe的朋友):
friendsIds = [1,4,5]
尝试从以下JSON获取匹配的ID并在friendsList视图中显示其名称:
[
{ "id": 1, "name": "Steve", "age": 22, "friends": [4] },
{ "id": 2, "name": "Mary", "age": 18, "friends": [1,3] },
{ "id": 3, "name": "Joe", "age": 43, "friends": [1,4,5] },
{ "id": 4, "name": "Tommy", "age": 19, "friends": [1] },
{ "id": 5, "name": "Leslie", "age": 27, "friends": [2,4] }
]
答案 0 :(得分:2)
我认为您可以使用map
和findWhere
的组合来执行此操作:
var friends = _.map(friendsIds, function(id) {
return _.findWhere(persons, { 'id': id });
});
答案 1 :(得分:0)
var friendsIds = [1,4,5];
var friends = [
{ "id": 1, "name": "Steve", "age": 22, "friends": [4] },
{ "id": 2, "name": "Mary", "age": 18, "friends": [1,3] },
{ "id": 3, "name": "Joe", "age": 43, "friends": [1,4,5] },
{ "id": 4, "name": "Tommy", "age": 19, "friends": [1] },
{ "id": 5, "name": "Leslie", "age": 27, "friends": [2,4] }
];
var filteredFriends = _.filter(friends, function(frnd){
return _.contains(friendsIds, frnd.id);
});
console.log(filteredFriends);
使用过滤器和地图查看性能差异 here
<强> FIDDLE 强>