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

Nikolay Komolov
Nikolay Komolov
23,033 Points

Passing a variable's contents to an object's property reference

Hello everybody! Could you help me, please?

I created a variable 'topic' and trying to pass its value as the property of the object (profile.points.topic).

var topic = 'Ruby';    
printMessage(username, profile.badges.length, profile.points.topic, topic);

It looks for 'topic' property which doesn't exist, instead of looking for the contents of the variable. How can I fix it?

Thanks!

2 Answers

Hey Nikolay,

You could set the property directly — like this:

var topic = 'Ruby';
profile.points.topic = topic;

console.log(profile.points.topic); // This would now evaluate to: 'Ruby'

Is that what you were asking?

Nikolay Komolov
Nikolay Komolov
23,033 Points

Thanks for the help! I was looking for a solution to replacing '.topic' part with the variable's contents. I want to access the property like this: profile.points.[var contents]. For instance, if topic = 'JavaScript', this line should become profile.points.JavaScript. :)

Assuming an object exists that looks something like this:

var profile.points = {
    'ruby': 78273,
    'javascript': 12334
}

Then, you could do this:

console.log(profile.points["javascript"]) // This would evaluate to: 12334

This "array-like" syntax is yet another way to access an object's properties in JavaScript. Does that answer your question?

You could also do this:

var profile.points = {
    'ruby': 78273,
    'javascript': 12334
}
var topic = 'ruby';

console.log(profile.points[topic]); // This would evaluate to 78273
Nikolay Komolov
Nikolay Komolov
23,033 Points

Yes, exactly! Thanks a lot :)

No problem :)