0

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>
  • Possible duplicate of [How do I loop through or enumerate a JavaScript object?](http://stackoverflow.com/questions/684672/how-do-i-loop-through-or-enumerate-a-javascript-object) – Alon Eitan May 09 '17 at 16:40
  • 1
    So you need to do recursion to loop over the objects inside. – epascarello May 09 '17 at 16:40
  • @epascarello They wrote _just returns "a"_ so I'm not sure if they need recursion, that's why I flagged it as duplicate of question without recursion – Alon Eitan May 09 '17 at 16:44

2 Answers2

1

If your object structure is fixed as mentioned in your question, you can loop twice to get the inner objects.

var p = {a: {b: 1}}
for (var key in p) {
  for (var k in p[key]) {
     console.log(k + " -> " + p[key][k] );
   }
  
}
Piyush
  • 1,162
  • 9
  • 17
1

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);
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55