Page 1 of 1

loop through JSON object

Posted: Wed May 09, 2007 1:34 pm
by GeXus
I have a json object, like this

Code: Select all

oNodeData = { "Nodes": [ 
	
		    { label: "One", id: "id1", parent_id: "" },
		    { label: "Two", id: "id2", parent_id: "" },
		    { label: "Three", id: "id3", parent_id: "" },
		    { label: "Four", id: "id4", parent_id: "id3" },
		    { label: "Five", id: "id5", parent_id: "" }
		]
I can get the various nodes, but how do I simply loop through it? Basically I want a loop that will loop 5 times, without setting 5 as a property in a for loop.

Posted: Wed May 09, 2007 1:48 pm
by Kieran Huggins
hmm.. confused by what exactly you're trying to do here.. you want to loop through your "Nodes" array 5 times? or you want to loop through all five elements of your Nodes array?

What are you actually trying to accomplish?

Posted: Wed May 09, 2007 1:53 pm
by GeXus
I just want to have a loop that will loop the for the # of "Nodes" - so it would simply loop 5 times, given this example.

Posted: Wed May 09, 2007 5:20 pm
by Kieran Huggins
you could use the .length property thusly:

Code: Select all

for (i=0; i<Nodes.length; ++i) {
 // do stuff to Nodes[i]...
}
or you could use jQuery's $.each() method thusly:

Code: Select all

$.each( Nodes, function(i, n){
  alert( "label #" + i + ": " + n.label );
  alert( "name #" + i + ": " + n.id );
});
I (of course) advocate using jQuery, as you'll likely find it speeds up your development and makes ajax much easier. There's a link in my sig.

Posted: Thu May 10, 2007 9:21 am
by GeXus
Fantastic... thanks!