Nastro
Nastro

Reputation: 1769

How to assign a value to an object property using variable?

I'm working on Reacr app. I have an object like this:

state = {
    property1: 'value',
    property2: 'value',
    property3: 'value',
    property4: 'value',
}

I want to assign a value to this object property through a function:

myFunc = (i) => {
     this.setState({
          this.state[i] = 'newValue'
     })  
}

But it can't be done because in this way I will directly mutate the state object. So I have a question how to get object property name and then assign a value to it? It would be nice if it can be possible in JavaScript to:

this.state[i] : 'ft-post ft-post-show'

Thank you for any ideas!

Upvotes: 0

Views: 71

Answers (1)

Shubham Khatri
Shubham Khatri

Reputation: 281626

You set the value using an object assignment with with dynamic key syntax like

myFunc = (i) => {
     this.setState({
          [i]:  'ft-post ft-post-show'
     })  
}

Upvotes: 4

Related Questions