2

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); 
1
  • traverse("value") -> for (var property in object) { /*property === 0*/ if (object.hasOwnProperty("0") /* true */) { traverse("v") } -> traverse("v") -> for (var property in object) { /*property === 0*/ if (object.hasOwnProperty("0") /* true */) { traverse("v") } -> ... Commented Nov 14, 2017 at 17:49

1 Answer 1

3

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.