I am trying to understand how recursive work with a nested js object which may have same key name. For example in the below object the keys are same in nest.
So when I am looping I am expecting obj[keys] will always go the first line(marked as //Line 1).
I am trying to understand how js will know consider which nest to loop if all the keys have same name. Not sure where I am going wrong in understanding
var obj = {
a: { // Line 1
a: { // Line 2
a: { // Line 3
sweptArea: 5
}
}
}
}
function loop(obj, keyName) {
for (var keys in obj) {
if (obj.hasOwnProperty(keys) && typeof obj[keys] === 'object') {
if (obj[keys][keyName] !== undefined) {
console.log(obj[keys][keyName])
} else {
// In my understanding in all the iteration it will point to obj.a marked as line one
loop(obj[keys], 'sweptArea')
}
}
}
}
loop(obj, 'sweptArea')
When you say obj[keys] is only looks for a key of that name on obj. That expression, by itself, does no recursion.
The value passed to the variable defined to the obj argument is different each time the function is called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With