Search code examples
javascriptloopsobjectfor-in-loop

Loop through object and get other objects (javascript)


I have an object with other objects inside of it that I need to access. How do I do it?

var obj = {a: {b: 1}} //I need to have access to b.

Right the for in loop just returns "a". The problem is I'm not trying to get a string inside an object, I'm getting an object inside an object.

var obj = {
	a: {r: "why cant i access"},
}

for(var o in obj){
	document.getElementById("div").innerHTML = o.r;
}
<div id="div"></div>


Solution

  • Although the answer posted by Piyush will work for the object you have given, it is not generic and will not work for all types of objects. Here's a script to read properties of any object:

    var obj = {a: {b:'2'}};
    
    var writeProperties = function (obj) {
      for(var prop in obj) {
        console.log("Property: ",prop,"Property Type:",typeof(obj[prop]));
        if(typeof(obj[prop]) == 'object') {
          writeProperties(obj[prop]);
        } else {
            console.log(prop + ':' + obj[prop]);
        }
        }
    }
    
    writeProperties(obj);