Creating a json array and json items with jquery?
I made a simple javascript class like this:
function Horse() {
this.color = 'brown';
this.speed = 'somewhat slow';
}
I attached a few instances to some elements, like this:
$("#horse1").data('d', new Horse());
$("#horse2").data('d', new Horse());
$("#horse3").data('d', new Horse());
now I 开发者_如何学Gowant to create a JSON array with a JSON representation of each horse object. So I'm doing this:
// How do I create an empty JSON array here?:
var myJsonArray = ?;
var children = $("#horses").children();
for (var i = 0, m = children.size(); i < m; i++) {
var panel = children[i];
var horse = $(panel).data('h');
// And how do I create a JSON rep of my horse here?
var myJsonHorse = new JsonHorse(?);
// Finally, how do I add it to the json array?
myJsonArray.push(myJsonHorse);
}
yeah my end goal is to have a single json array of all the horses after iterating over all the children - not sure if this should be done in plain javascript or in jquery?
Thanks
---------------- Edit -------------------
Sorry, my end goal is to then convert the array to a string, so I have one large json array converted to a string that I can submit to an ajax call that will get processed by my server.
To declare an array you just need the Array Literal notation:
var myArray = [];
The push
method will work without problems.
Another possibility is to use the $.map
method:
var myArray = $("#horses").children().map(function (index, el) {
return $(el).data('d');
}).get();
// Will return an array containing:
// [{"color":"brown","speed":"somewhat slow"},
// {"color":"brown","speed":"somewhat slow"},
// {"color":"brown","speed":"somewhat slow"}]
Check an example here.
Then to convert that array to a JSON string, you can use the JSON.stringify
method (available natively on almost all browsers, for IE < 8 you can use json2.js).
精彩评论