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 Node.js Basics (2014) Building a Command Line Application Perfecting: Getting Multiple Profiles

Kevin Faust
Kevin Faust
15,353 Points

how 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

Hi 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
Kevin Faust
15,353 Points

yup but it gives back undefined

What's an example value that topic would be? I had assumed a string.

Kevin Faust
Kevin Faust
15,353 Points

doh nevermind i was typing in a lower case parameter when the property key is all upper case. thanks for the help

Kevin Faust
Kevin Faust
15,353 Points

forgot about case sensitivity when accessing properties

Ok, glad you got it working.