Reputation: 42049
I'm working on codecademy.com JavaScript tutorial. This lesson on objects. I have a feeling this problem is fairly simple, but I'm not getting the answer. If I understood the instructions better, the answer might be clearer to me.
I set the value to the variable aProperty, and now I'm supposed to follow the instructions in the final comment, i.e. print the value of the first property using the variable "aProperty". I've included the "intro to the lesson" below to help explain what the lesson is trying to teach.
The Question: Assuming I set the variable aProperty correctly, how would you retrieve the first value of the James object using the variable aProperty.
var james = {
job: "programmer",
married: false
};
// set to the first property name of "james"
var aProperty = james.job;
// print the value of the first property of "james"
// using the variable "aProperty"
Intro to lesson
And finally, let's go over retrieving property values. Throughout this section, we've been using dot notation to get the value of an object's property:
someObj.propName
However, remember that we can also use bracket notation:
someObj["propName"]
An advantage of bracket notation is that we are not restricted to just using strings in the brackets. We can also use variables whose values are property names:
var someObj = {propName: someValue}; var myProperty = "propName"; someObj[myProperty]
The last line is exactly the same as using someObj["propName"].
Take advantage of the ability to use variables with bracket notation.
In line 7, set aProperty to a string of the first property in james (ie. the job property).
Then print james's job using bracket notation and aProperty.
Upvotes: 2
Views: 3756
Reputation: 459
Try something like this:
var james = {
job: "programmer",
married: false
};
var aProperty = "job";
console.log( james[aProperty] );
Upvotes: 0