Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Not able to understand recursive behaviour in nested javascript object

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')
like image 825
brk Avatar asked Jun 19 '26 16:06

brk


1 Answers

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.

like image 71
Quentin Avatar answered Jun 21 '26 06:06

Quentin