简体   繁体   中英

how to get only the attributes of all the models in a collection

I have a collection as shown below

window.courses = new Courses();

and some where in my code I am trying to access the attributes of the collection. I have used pluck to get only single attribute which is courseName

for example:

var courseName = window.courses.pluck('Name');

I can get all the courses names(single attribute) in my collection, but is there a way that I can get each items name and id from Courses collection,something like

var courseList = window.courses.pluck('Id','Name');

using below code

var courseList = window.courses;

I get all the extra details which I dont need,so can someone suggest how to get required attributes of all the models inside a collection

Thanks in advance

The standard Backbone pluck function only supports reading one attribute value.

You could write your own, for example:

Backbone.Collection.prototype.pluckMany = function (attrs) {
    return _.map(this.models, function (model) {
        return _.pick(model.attributes, attrs);
    });
}

var courseList = window.courses.pluckMany(['Id', 'Name']);

NB: Untested code!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM