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 trialKevin Faust
15,353 Pointshow to access an object property by variable
i want to use the passed in paramter value as the property key.
so heres an example of what i mean:
function getPoints(topic) {
return profile.points.topic;
//profile.points is an object literal with a bunch of properties. i want to access the property that was passed in via paramter
}
unfortunately it tries to find a property called 'topic' and not the variable value of 'topic'. does anyone know a solution? i tried everything i could think of
thanks
1 Answer
Jason Anello
Courses Plus Student 94,610 PointsHi Kevin,
Have you tried accessing with bracket notation yet?
return profile.points[topic];
Don't put topic
in quotes, otherwise you'll be back to trying to access a property named topic
Kevin Faust
15,353 PointsKevin Faust
15,353 Pointsyup but it gives back undefined
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsWhat's an example value that topic would be? I had assumed a string.
Kevin Faust
15,353 PointsKevin Faust
15,353 Pointsdoh nevermind i was typing in a lower case parameter when the property key is all upper case. thanks for the help
Kevin Faust
15,353 PointsKevin Faust
15,353 Pointsforgot about case sensitivity when accessing properties
Jason Anello
Courses Plus Student 94,610 PointsJason Anello
Courses Plus Student 94,610 PointsOk, glad you got it working.