m-use
m-use

Reputation: 363

How to access a key/value pair with a variable?

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

Answers (1)

Gonzalo.-
Gonzalo.-

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

Further Info

Upvotes: 1

Related Questions