Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  61] [ 6]  / answers: 1 / hits: 18026  / 13 Years ago, wed, september 28, 2011, 12:00:00

I want to create an array of specific attribute values from a Backbone collection.



var days = _.select(
this.collection.models,
function(model) {
return model.attributes.type === 'session';
}
);

days = _.pluck(days, 'attributes'),
days = _.pluck(days, 'date');


This works, but seems inefficient. Is there a way to accomplish the same thing without having to define days three times?


More From » backbone.js

 Answers
0

pluck is a convenience method that wraps map, and map is available directly on the collection, which should make this easier.



assuming you are trying to get the date attribute out of your models, you can do this:



days = this.collection.map(function(model){
return model.get('date');
});


your select call is also available on the collection directly, as the filter method.



days = this.collection.filter(function(model){ 
return model.attributes.type === 'session';
});


you can chain these two together, but it helps if you define methods separately:



var sessionFilter = function(model){
return model.attributes.type === 'session';
};
var getDate = function(model){ return model.get('date'); }

days = this.collection.filter(sessionFilter).map(getDate);


this should return the results your looking for... or something close to this at least :)


[#89874] Tuesday, September 27, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sherryd

Total Points: 254
Total Questions: 92
Total Answers: 89

Location: Equatorial Guinea
Member since Sun, Feb 14, 2021
3 Years ago
;