简体   繁体   中英

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.

You can use bracket notation:

var prop = 'like';

var like = this.state[prop];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM