0

I have a field like this:

   const updatedForm = Object.assign({}, this.state.form)
    updatedForm[name] = value;

Is there a way I can use the spread operator or ES6 to further simplify this?

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
lost9123193
  • 10,460
  • 26
  • 73
  • 113
  • [`...` is not an operator!](https://stackoverflow.com/questions/37151966/what-is-spreadelement-in-ecmascript-documentation-is-it-the-same-as-spread-oper/37152508#37152508). Object rest/spread does not exist in ES6. Are you limited to ES6? – Felix Kling Jul 03 '19 at 04:08
  • @FelixKling thanks for the link! no I'm just cleaning up my code in react – lost9123193 Jul 03 '19 at 04:39
  • I find it nonsemantic to declare a `const` that you fully intend to modify. You *can* do it, but it just doesn't look right. Why not use *let* (and save some typing)? ;-) – RobG Jul 03 '19 at 04:40
  • @RobG oh that's a good point... I'll make that update as well. Thanks! – lost9123193 Jul 03 '19 at 04:46

3 Answers3

2

Yes you can:

const updatedForm = { ...this.state.form, [name]: value };

Note the square brackets around [name]. This is due to the use of dynamic property names in your original code - this is how you do it in a literal.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
0

This would have the same effect as:

const updatedForm = {...this.state.form}

updatedForm[name] = value

Which in a sense is shorter and achieves the same goal.

From @Felix Kling

const updatedForm = {
  ...this.state.form,
  [name]: value
}

So you can define the new key-value pair during the creation of your newly spreaded object.

In practice, I'm assuming with React. you could do something like:

class Form extends React.Component{
    state = {
        form: {
            name: "",
            age: ""
        }
    }

    handleOnChange = (e) => {
        const { name, value } = e.target

        const updatedForm = {
            ...this.state.form,
            [name]: value
        }

        this.setState({
            form: updatedForm
        })
    }

    render(){
        const { form } = this.state
        return(
            <div>
                <form>
                    <input name="name" value={form.name} onChange={this.handleOnChange}/>
                    <input name="age" value={form.age} onChange={this.handleOnChange}/>
                </form>
            </div>

        )
    }
}

See sandbox: https://codesandbox.io/s/objective-galois-ifogc

Chris Ngo
  • 15,460
  • 3
  • 23
  • 46
0

You can do this in one line using Object.assign too:

const updatedForm = Object.assign({}, this.state.form, { [name]: value })
adiga
  • 34,372
  • 9
  • 61
  • 83