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>

3
  • Possible duplicate of How do I loop through or enumerate a JavaScript object? Commented May 9, 2017 at 16:40
  • 1
    So you need to do recursion to loop over the objects inside. Commented May 9, 2017 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 Commented May 9, 2017 at 16:44

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.