I have a 3 level object with a code that iterates for each level, if in case the levels increase I would like to improve it so that it is more dynamic, can recursion be used, or even non-recursion but how could it be optimized?
var obj = [{
"seccion1": {
"level1": {
first: "John",
last: "Doe"
},
"level2": {
first: "juan",
last: "perez"
}
}
}]
obj.forEach(function(item) {
Object.keys(item).forEach(function(key) {
let value = item[key];
Object.keys(value).forEach(function(key2) {
console.log(value[key2].first, value[key2].last);
});
});
});
The result should be:seccion1 level1 john doe level2 juan perez
You must make a recursive function, you avoid repeating code:
We can avoid the last iteration, but you need to know the last iteration, you avoid traversing the object again, the example below:
Using the divide and conquer strategy : An object of this type can have as properties a primitive type (string, number, bigint, null, undefined...) or another nested object.
So you have a base case: the property is a primitive. The recursive case is when the property of the object is another object:
Limiting Pablo Lozano's answer, a couple of lines of code can be reduced by changing the
if
by conditional?
and:
initializing the variabletext
when declaring the function, being as follows:And this would be the most optimal way to iterate a multi-level object, greetings.
I show you two alternatives that you can optimize according to your criteria to obtain the result you ask for.