0

I am getting a following JSON(/users.json) which contains users:

[
  [
    { "id": "43343", "project_id": "1", "username": "Amy" }
    { "id": "34244", "project_id": "1", "username": "Tommy" }
  ],
  [
    { "id": "76575", "project_id": "2", "username": "Izzy" }
    { "id": "13322", "project_id": "2", "username": "Sam" }
  ],
  { "id": "09983", "project_id": "3", "username": "Max" }
]

When project has one user I get one user hash which is not in array.

I would like to build a Backbone collection with all users. How to do that?

1
  • dude..why are you nesting arrays like that? Commented Nov 13, 2014 at 7:13

2 Answers 2

4

You provide an array of arrays of users. So to fetch all users in the init method, you can give it data but as an array of users, i.e. you will flatten this original array of arrays once with underscore flatten method :

data = _(data).flatten(true);

Then the collection constructor will natively understand your json array.

But maybe you already do this transformation in the fetching method and this is not the problem you are facing..

Sign up to request clarification or add additional context in comments.

Comments

1

If you have defined a collection (say userCollection) with a user model you should be able to simply do something like this:

var col;
$.getJSON("/users.json", function(data) {
    col = new userCollection(data);
});

This would more likely be done in the fetch function of the collection, but the principle here is that you can pass an array of objects to a collection and it will marshal all from json to backbone models.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.