Reputation: 363
I am looking to access a key/value pair dynamically using the a variable. I can get the value I'm looking for using topics.social.color
, but the topic will change based on the user's selection. How can I dynamically get the topic color using a variable for the topic?
let topic = 'social';
const topics = {
social: {
color: 'red'
},
emotional: {
color: 'blue'
},
physical: {
color: 'green'
}
};
console.log(topics.topic.color); // this does not work
CodePen: https://codepen.io/m-use/pen/XWJKBMB
Upvotes: 0
Views: 167
Reputation: 12682
this should do the trick
topics[topic].color
let topic = 'social';
const topics = {
social: {
color: 'red'
},
emotional: {
color: 'blue'
},
physical: {
color: 'green'
}
};
console.log(topics[topic].color);
Upvotes: 1