how to iterate over inner objects / property in an object

I have an object which has inner objects and properties defined like this:

var obj = {obj1 : { "prop1" : "nothing", "prop2" : "prop"},
        obj2 : {"prop1" : "nothing", "prop2" : "prop"},
        pr1 : "message",
        pr2 : "mess"
};

Normally to iterate every property of an object , the for .. in loop can do the trick

for (property in obj){
    if (obj.hasOwnProperty(property)){
        console.log(property + "   " + obj[property]);
    }
}

the console displayed :

obj1 [object Object]
obj12 [object Object]
pr1 message
pr2 mess

However how to iterate the inner objects (obj1, obj2) and their own properties (prop1,prop2) ?

Answers


Recursion is your friend:

function iterate(obj) {
    for (var property in obj) {
        if (obj.hasOwnProperty(property)) {
            if (typeof obj[property] == "object")
                iterate(obj[property]);
            else
                console.log(property + "   " + obj[property]);
        }
    }
}

Note: don't forget to declare property locally using var!


That's great anwsers, although the array cases is not covered, here's my contribution:

var getProps = function (obj) {
    for (var property in obj) {
        if (obj.hasOwnProperty(property) && obj[property] != null) {
            if (obj[property].constructor == Object) {
                getProps(obj[property]);
            } else if (obj[property].constructor == Array) {
                for (var i = 0; i < obj[property].length; i++) {
                    getProps(obj[property][i]);
                }
            } else {
                console.log(obj[property]);
            }
        }
    }
}
getProps(myObject);

To simply display the object structure, I often use: console.log (JSON.stringify (obj))


You can use recursion to achieve that:

function Props(obj) {

 function getProps(obj){
  for (var property in obj) {
    if (obj.hasOwnProperty(property)){
        if (obj[property].constructor == Object) {
           console.log('**Object -> '+property+': ');
           getProps(obj[property]);
        } else {
           console.log(property + " " + obj[property]);
        }
    }
  }
 }
 getProps(obj);
}

see http://jsfiddle.net/KooiInc/hg6dU/


Need Your Help

Why are stack overflows still a problem?

programming-languages stack memory-management

This question is mystifying me for years and considering this site's name, this is the place to ask.

OPENJSON does not work in SQL Server?

sql-server json sql-server-2016

I want to use JSON functions in SQL Server 2016, but when I try to execute OPENJSON function, I get the following error: