I have a for loop which should loop through an object. But this object can have many other object levels inside it. How can I make a function that should make for loops inside for loops as many levels deeps as I want?
Something like this, where the lvl variable would be the number of levels it should dive in:
var lvl = 5;
for (var i = 0; i < groups.length; i++) {
var groups = groups[i];
for (var i = 0; i < groups.length; i++) {
var groups = groups[i];
for (var i = 0; i < groups.length; i++) {
var groups = groups[i];
}
}
}
For example, if I have the following object tree:
var foo = {
child: {
grand:{
greatgrand: {
}
}
}
}
How can I console log all the object tree names just by diving to a specific level in the foo object?
dive(2); // would dive to level two (grand)
// would return the following in the console
child
grand
forloop so one loop is not overwriting the variables from the others or you can make a function to do the looping and call it recursively.i(andgroups) represents the same variable and the multiple occurrences ofvaris irrelevant. Search for "variable hoisting" for more details. (With that aside, recursion is pretty natural for "N-levels" although using a stack would be another solution.)