Search code examples
javascriptobjectpropertiestraversal

JS- Traverse object


I have a javascript object that has nested objects as properties. I would like to traverse this javascript object, to get a list of all the properties of every object inside the object.

I wrote a function to do this, but for some reason when I run the function I get an infinite loop of 0's. Does anyone know how the reason and solution for this issue?

var test = {a: {b: { c: 'value '}}}; 

var traverse = function(object){
  for (var property in object) {
    if (object.hasOwnProperty(property)) {
        console.log(property); 
        traverse(object[property])
    }else {
      console.log('None'); 
      break;
    }
  }
}
traverse(test); 

Solution

  • You have a string at the end and this string is separated into a single characters with one index zero. From this string, the character at position zero is taken and the recursion is called again with a single character.

     key          value           comment
    -----  -------------------  -----------
      a    {
               b: {
                   c: "value "
               }
           }
    
      b    {
               c: "value "
           }
    
      c    "value "
    
      0    "v"
      0    "v"
      0    "v"                  and so on
    

    This character has an index zero and so on.

    To prevent such habit, you could check for onyl truthy values (prevent null) and type of objects to get traversed.

    var test = { a: { b: { c: 'value ' } } };
    
    var traverse = function (object) {
        for (var property in object) {
            if (object.hasOwnProperty(property)) {
                console.log(property);
                if (object[property] && typeof object[property] === 'object') {
                    traverse(object[property]);
                }
            } else {
                console.log('None');
            }
        }
    }
    traverse(test);