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 want 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.
-
What are you doing with the object afterwards? A normal array seems to be appropriate here, so I'm not sure what you're after/what the end-game is.Nick Craver– Nick Craver2010年06月16日 00:19:54 +00:00Commented Jun 16, 2010 at 0:19
-
Oh yeah I want to make it one long json string so I can use it in an ajax call, thanks.user246114– user2461142010年06月16日 03:44:44 +00:00Commented Jun 16, 2010 at 3:44
1 Answer 1
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).
3 Comments
$.data(el, 'd') would be a lot more efficient in this case, no need to create the jQuery wrappers unless you need to.JSON.stringify method to convert that array and the object elements it has to JSON, that method is natively available on all browsers except IE <= 7, you can add the json2.js library to your page to make it work on IE <= 7.