Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
    }
}
like image 831
Ben Avatar asked Dec 03 '15 17:12

Ben


People also ask

How do you change the properties of a nested object?

To update nested properties in a state object in React: Pass a function to setState to get access to the current state object. Use the spread syntax (...) to create a shallow copy of the object and the nested properties. Override the properties you need to update.

How to access nested properties in JS?

Values of an object's properties can be another object. We can access nested properties of an object or nested objects using the dot notation (.) or the bracket notation []. Nested properties of an object can be accessed by chaining key or properties names in the correct sequence order.

What is computed property name in JavaScript?

Computed property names That allows you to put an expression in brackets [] , that will be computed and used as the property name. This is reminiscent of the bracket notation of the property accessor syntax, which you may have used to read and set properties already.

What is nested properties?

The value of many properties is a reference to another resource. If the value of a property is a reference to a resource, the PropertyRequest might contain a NestedPropertyName object instead of the PropertyName object for the property.


1 Answers

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 });
}
like image 151
Jordan Running Avatar answered Oct 23 '22 14:10

Jordan Running