Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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.