javascript - Retrieve list of a specific attribute from a Backbone collection -
i'm looking way to, backbone collection, retrieve kind of array of 1 specific attribute.
var somemodel = backbone.model.extend({ defaults: function() { return { attr1: "something", attr2: "something", attr3: "darkside" }; } }); var somecollection = backbone.collection.extend({ model: somemodel, url: '/data.json', });
now assume have above , want collection/array/similar attribute 'attr3'. there nice way (not manually iterating through somecollection , building new collection)? understanding underscore function "filter" returns entire somemodel based on premise, i.e. not want. ideas?
thanks
if want 1 attribute, can use _.pluck
somecollection.pluck('attr3');
for multiple attributes, can combine _.map on collections , _.pick on models
somecollection.map(function (model) { return model.pick('attr2', 'attr3'); });
and demo http://jsfiddle.net/nikoshr/qpyxc/1/
or, more concise version using _.invoke
somecollection.invoke('pick', 'attr2', 'attr3');
Comments
Post a Comment