Creating a json array and json items with jquery? -
I have created a simple JavaScript class like this:
function Horse () {this Color = 'brown'; This.speed = 'Slow to some extent'; }
I have attached some examples on some elements, such as:
$ ("# horse1"). Data ('d', new horse ()); $ ("# Mare 2") Data ('d', new horse ()); $ ("#Hors 3"). Data ('d', new horse ());
Now I want to create a JSON array with a JSON representation of a horse object. So I am doing this:
// How do I create an empty JSON array here? Var myJsonArray = ?; Var Kids = $ ("#Hors") Children (); For (var i = 0, m = children.size (); i & lt; m; i ++) {var panel = children [i]; Var horse = $ (panel) .data ('h'); // And how do I create a JSON representative of my horse? Var myJsonHorse = New Jason Horse (?); // Finally, how do I add it to the JSON array? MyJsonArray.push (myJsonHorse); }
Yes, my last goal is to have a Jason array of all horses after running all the children - is not it sure that it should be done in plain javascript or jquery?
Thanks
---------------- Edit ----------------- -
Sorry, my ultimate goal is to convert the array into a string, so I have a large Jason array that gets converted into a string that I can submit in an AJAX call Which will be processed by my server.
To declare an array you only need an array literal signaling:
< Pre> var MyArray = [];
Push
method will work without any problems.
Another possibility is to use the method:
Var myArray = $ ("#Hors"). Children () Map (Tasks (Index, L) {Return $ (L). Data ('D');}). () get receive; // will contain an array: // [{"color": "brown", "speed": "slow to a certain extent"}, // {"color": "brown", "speed": "to a lesser extent Slow "} Then change an array. In a JSON string, you can use the JSON.stringify
method (for almost all browsers, for IE, Nature can use IE).
Comments
Post a Comment