loop through JSON object

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

loop through JSON object

Post 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.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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?
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post 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.
User avatar
Kieran Huggins
DevNet Master
Posts: 3635
Joined: Wed Dec 06, 2006 4:14 pm
Location: Toronto, Canada
Contact:

Post 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.
GeXus
Forum Regular
Posts: 631
Joined: Sat Mar 11, 2006 8:59 am

Post by GeXus »

Fantastic... thanks!
Post Reply