Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone.js: Build JSON array from collection

I have a backbone collection Platforms. The structure of Platforms looks like this:

Platforms
  PlatformList
    models
      0: Platform
        attributes
          id: 1
          name: "some name"
      1: Platform
        attributes
          id: 2
          name: "some other name"

I need to extract the attributes from the models within the collection, and build a JSON array in the following format:

[{"id":1,"name":"some name"},{"id":2,"name":"some other name"}]

Calling Platforms.models.toJSON() or JSON.stringify(Platforms.models) results in a literal string "[[object Object], [object Object]]"

How can I build the JSON array that I need from this collection?

like image 317
Kevin Whitaker Avatar asked Mar 05 '12 15:03

Kevin Whitaker


1 Answers

you should not do platforms.models.toJSON() but instead call toJSON on the collection itself!

Platforms.toJSON()

check the following jsfiddle on this solution http://jsfiddle.net/saelfaer/TP9NE/2/

like image 183
Sander Avatar answered Sep 22 '22 10:09

Sander