Is there a way (in jQuery or JavaScript) to loop through each object and it’s children and grandchildren 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
You’re looking for the
for...inloop:Be aware that
for...inloops 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 thehasOwnPropertymethod to check to see if the property belongs only to that object:Performing the loop recursively can be as simple as writing a recursive function: