views:

90

answers:

1

Is there a way (in jquery or javascript) to loop through each object and it's children and gandchildren and so on. if so... can i also read their name?

example

foo :{
  bar:'',
  child:{
    grand:{
      greatgrand: {
        //and so on
      }
    }
  }
}

so the loop should do something like this...

loop start
   if(nameof == 'child'){
     //do something
   }
   if(nameof == 'bar'){
     //do something
   }
   if(nameof =='grand'){
     //do something
   }
loop end

I know this is stupid code but i tried to make it understandable :)

btw this is for a jquery UI, as i am clueless how to go on about this.

thanks

+3  A: 

You're looking for the for...in loop:

for (var key in foo)
{
    if (key == "child")
        // do something...
} 

Be aware that for...in loops will iterate over any enumerable properties, including those that are added to the prototype of an object. To avoid acting on these properties, you can use the hasOwnProperty method to check to see if the property belongs only to that object:

for (var key in foo)
{
    if (!foo.hasOwnProperty(key))
        continue;       // skip this property
    if (key == "child")
        // do something...
}

Performing the loop recursively can be as simple as writing a recursive function:

function eachRecursive(obj)
{
    for (var k in obj)
    {
        if (typeof obj[k] == "Object")
            eachRecursive(obj[k]);
        else
            // do something... 
    }
}
Andy E
I was thinking of that eachRecursive function, the only thing that i was afraid that if i did something wrong on the code would crash the browser from exhoustion...(cn't spell it ) i will give it a go :)
Val
@Val: it would be difficult to crash the browser with object recursion. The object would need to contain a reference to itself as one of the properties :-)
Andy E