Exorcismus
Exorcismus

Reputation: 2482

How to access object property using string variable?

If I have an object like below:

this.state = {
  like: {
    count: 100,
    clicked: false
  },
  dislike: {
    count: 25,
    clicked: false
  }
};

If have a variable name of var prop = 'like', how can I get the value of this.state.like using prop value?

I tried named property [this.state.prop] but it's not working.

Upvotes: 0

Views: 123

Answers (1)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

You can use bracket notation:

var prop = 'like';

var like = this.state[prop];

Upvotes: 3

Related Questions