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 trialNikolay Komolov
23,033 PointsPassing 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
miikis
44,957 PointsHey 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
23,033 PointsYes, exactly! Thanks a lot :)
miikis
44,957 PointsNo problem :)
Nikolay Komolov
23,033 PointsNikolay Komolov
23,033 PointsThanks 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. :)
miikis
44,957 Pointsmiikis
44,957 PointsAssuming an object exists that looks something like this:
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?
miikis
44,957 Pointsmiikis
44,957 PointsYou could also do this: