Creating a json array and json items with jquery?

Posted by user246114 on Stack Overflow See other posts from Stack Overflow or by user246114
Published on 2010-06-16T00:07:50Z Indexed on 2010/06/16 0:12 UTC
Read the original article Hit count: 279

Filed under:

Hi,

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

© Stack Overflow or respective owner

Related posts about jQuery