0

This seems rather basic but I am having an impossible time trying to figure this out... How do I access the property value of a property that is in an object within an object?

Ex:

var myObj = {numberOne: {type1: "one", type2:"two"}};

In my case, numberOne is constantly changing as are the property values of the properties within it ("one", "two"). What does not change are the property names themselves (type1, type2). I am looking for a way to access the property value of type1 ("one") as it is the only value I'm interested in working with.

My thought is that I need to create a key for numberOne and use a for... in loop but I'm not pulling up the correct results. I can only get as far as extracting the property names.

var myObj = {numberOne: {type1: "one", type2: "two"}};
var key = Object.keys(myObj)[0];

for (var prop in myObj[key]){
  console.log(prop);
}
4
  • possible duplicate of How do I access properties of a javascript object if I don't know the names? Commented May 19, 2015 at 19:47
  • 2
    console.log(myObj[key][prop]); Commented May 19, 2015 at 19:48
  • 1
    Also, your object literal syntax is wrong. Should be: var myObj = {numberOne: {type1 : "one", type2 : "two"}}; There are no = in an object literal Commented May 19, 2015 at 19:50
  • Thanks for the help. And yes, realized I was using = instead of : and fixed that. Commented May 19, 2015 at 19:57

0

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.