javascript Backbone.js:从集合构建 JSON 数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9569696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone.js: Build JSON array from collection
提问by Kevin Whitaker
I have a backbone collection Platforms
. The structure of Platforms
looks like this:
我有一个骨干收藏Platforms
。的结构Platforms
看起来像这样:
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:
我需要从集合中的模型中提取属性,并按以下格式构建一个 JSON 数组:
[{"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]]"
调用Platforms.models.toJSON()
或JSON.stringify(Platforms.models)
产生文字字符串"[[object Object], [object Object]]"
How can I build the JSON array that I need from this collection?
如何从这个集合中构建我需要的 JSON 数组?
回答by Sander
you should not do platforms.models.toJSON() but instead call toJSON on the collection itself!
你不应该做platforms.models.toJSON(),而是在集合本身上调用toJSON!
Platforms.toJSON()
check the following jsfiddle on this solution http://jsfiddle.net/saelfaer/TP9NE/2/
检查此解决方案的以下 jsfiddle http://jsfiddle.net/saelfaer/TP9NE/2/