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

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 :)