Skip to content
Advertisement

update nested object with (ES6) computed property name

In my case, I’m using React.js and I would like to dynamically update the values in the deployOptions object.

For example –

initial state looks like:

getInitialState() {
    return {
      deployOptions: {
        config: null,
        action: 'deploy',
        env: 'qa'
      }
    }
  }

Obviously this is not correct – but this is what I’m trying to achieve

configOptionChange(option) {

    // option -> { key: 'env', value: 'prod' }

    this.setState({
      [deployOptions.option.key]: option.value
    });
  }

so that my state would then be

{
    deployOptions: {
      config: null,
      action: 'deploy',
      env: 'prod' // only this changes
    }
}

Advertisement

Answer

It’s not especially pretty, but I think this is the best you can do with ES6:

configOptionChange({ key, value }) {
  this.setState({
    ...this.state,
    deployOptions: {
      ...this.state.deployOptions,
      [key]: value
    }
  });
}

It’s basically equivalent to your own Object.assign solution but using the ES6 spread (...) operator (and argument destructuring for good measure).

Here’s a second option that isn’t as clever but feels a little cleaner to me:

configOptionChange({ key, value }) {
  const { deployOptions: prevDeployOptions } = this.state;
  const deployOptions = { ...prevDeployOptions, [key]: value };
  this.setState({ ...this.state, deployOptions });
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement