How to convert an array to Collection in backbone

Abhishek Singh Thakur picture Abhishek Singh Thakur · Jul 22, 2015 · Viewed 8.6k times · Source

I have an array defined as:

this.noOfHouseHold = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20"];

I'm trying to convert it to a Backbone Collection as:

var adultListCollection = new Backbone.Collection(this.noOfHouseHold);

It gives me the list but for 2 digit numbers, it shows something like this:

attributes: Object
0: "1"
1: "1"

I'm not able to understand as to what is wrong here or is it the wrong way I'm converting my array to collections. Please suggest. Thanks in advance!

Answer

nikoshr picture nikoshr · Jul 22, 2015

A Backbone collection expects a list of models/hashes of attributes that can be converted to a model but you have a plain array.

You will have to transform your array to a list of hashes. Assuming your values are the ids of your models :

var lst = _.map(this.noOfHouseHold, function(val) {
    return {id: val};
});
var adultListCollection = new Backbone.Collection(lst);