Converting Array of Arrays to Backbone Collection of Models
11,469
Reshape your raw data to look more like:
[{ first: 1, second: 2, third: 3, fourth: 4 }, { first: 5, second: 6, third: 7, fourth: 8}]
Assuming you have a model and collection defined something like:
var Model = Backbone.Model.extend({});
var Collection = Backbone.Collection.extend({
model: Model
});
Then just pass the array of attribute hashes into the reset method:
var results = [{ first: 1, second: 2, third: 3, fourth: 4 }, { first: 5, second: 6, third: 7, fourth: 8}];
var collection = new Collection();
collection.reset(results);
var model = collection.pop();
console.log(JSON.stringify(model.toJSON());
Author by
praks5432
Updated on June 05, 2022Comments
-
praks5432 almost 2 years
new to Backbone and underscore js here.
I have an array of arrays that I want to convert to a collection of models.
So it's like
{ {1, 2, 3, 4}, {5, 6, 7, 8}}
The second level of arrays is what's going into a backbone model. Right now, I have
collection.reset(_.map(results, (indvidualResults) -> new model(individualResults))
Which doesn't work as when I do a console.log(collection.pop) I get a function printed out. I think this is because I'm working with an array of arrays (but I could be wrong). How do I convert the second array into a model and then put that into a collection?
-
mu is too short almost 12 years(1) What does your data really look like? (2) Why are you doing the
_.map
whenCollection#reset
will do all that for you? (3) Collections have apop
method so of courseconsole.log(collection.pop)
gives you a function. -
Ricardo Tomasi almost 12 yearsDo you mean
console.log(collection.pop())
?console.log(collection.pop)
*should* give you a function.
-
-
Stanislav Ostapenko over 9 yearscollection.reset(results); works fine. But looks like it doesn't execute .parse() method on each model.