问题
I'm basically trying to do what is done with this question, but with an array and return all objects using the values of the corresponding array, not just the value: Filter backbone collection by attribute value
My natural instinct is to use _.filter or _.partition on the persons collection, but am confused on how these are being compared & returned and am not getting the desired outcome.
With the following, passing the id in via the router:
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 });
});
},
I have a friendsIds array (Joe's friends):
friendsIds = [1,4,5]
And trying to get the matched ids from the following JSON and display their names in my friendsList view:
[
{ "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] }
]
回答1:
I think you could use a combination of map and findWhere to do this:
var friends = _.map(friendsIds, function(id) {
return _.findWhere(persons, { 'id': id });
});
回答2:
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);
See the difference in performance with filter and map here
Make use of filter and contains
FIDDLE
来源:https://stackoverflow.com/questions/22263676/backbone-js-underscore-js-filtering-a-collection-vs-array