Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How do you use variables to reference a nested property within a nested object? How do you chain the reference?

When using variables you can only use the bracket notation, so if you have to reference a child within several levels how do you write the expression? Assume the name of each sub-property or sub-object is variable or unknown.

Do I need to write getters and setters?

2 Answers

yeah! I'm glad it worked!

It's important to understand WHY you would use the bracket notation, which is what I think you where getting at in your question. The bracket is used generally when you have a changing variable, so let's say you had an object like....

var object = {
 1: 'one',
2: 'two',
3: 'three',
}

and you wanted to iterate through this object and do something with it, you may attempt to access/manipulate the object with dot notation like so...

  for ( i = 1; i > 3; i++) {
   document.write(object.i)
 }

however, the above will be telling the document.write() to look for an object, and find the key i inside of it - not the varaible I that we are using in the for loop. THIS is when you'd use bracket notation to access the changing variable, like so...

   for ( i = 1; i > 3; i++) {
   document.write(object[i])
 }

hope that leads to higher understanding!

Yes that is exactly what I was trying to understand. Thanks again! :)

I'm not sure I understand your question! But I'll give it a shot!

var object = {
 subObbject : {
  subSubObject: {
   value: 'value';
  }
 }
}

lets say you have the above object. If you wanted to grab the value property from the subSubObject, you would write the following code...

//bracket notation
var whatIWant = object[subObject][subSubObject][value];

//or

//dot noation
var whatIWant = object.subObject.subSubObject.value;

the above will traverse through the object along the 'path' supplied to grab the value you desired.

Thank you so much, it turns out I had already tried it in the bracket notation but somehow it did not work! Today with a fresh mind I just did it! Thanks so much it really helped!

What I writing is a program that updates objects properties using a function that takes as parameters the id, the property and the value of the object and then updating them in some cases or not in some others. The bracket notation is therefore used since I'm using variables.

Thanks again