[javascript] Recursively looping through an object to build a property list

You'll run into issues with this if the object has loop in its object graph, e.g something like:

var object = {
    aProperty: {
        aSetting1: 1
    },
};
object.ref = object;

In that case you might want to keep references of objects you've already walked through & exclude them from the iteration.

Also you can run into an issue if the object graph is too deep like:

var object = {
  a: { b: { c: { ... }} }
};

You'll get too many recursive calls error. Both can be avoided:

function iterate(obj) {
    var walked = [];
    var stack = [{obj: obj, stack: ''}];
    while(stack.length > 0)
    {
        var item = stack.pop();
        var obj = item.obj;
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object") {
                  var alreadyFound = false;
                  for(var i = 0; i < walked.length; i++)
                  {
                    if (walked[i] === obj[property])
                    {
                      alreadyFound = true;
                      break;
                    }
                  }
                  if (!alreadyFound)
                  {
                    walked.push(obj[property]);
                    stack.push({obj: obj[property], stack: item.stack + '.' + property});
                  }
                }
                else
                {
                    console.log(item.stack + '.' + property + "=" + obj[property]);
                }
            }
        }
    }
}

iterate(object);