Home > Enterprise >  Use a variable for object name to be changed with spread operator (Reactjs)
Use a variable for object name to be changed with spread operator (Reactjs)

Time:09-30

I'm fairly new to reactjs and javascript, so I'm not sure of the right syntax.

I want to use the spread operator to update an object but instead of hardcoding the field name I want it to be a variable, but it reads it as a field name instead of taking the variable value as the field name.

For example, This is my variable:

let [obj, setObj] = useState({'title': '', 'body': ''})

I update it like this:

const onChangeCallBack(field, value){
   if(field === 'body'){
       setObj(obj => ({...obj, 'body': value}))
   }else if(field === 'title'){
       setObj(obj => ({...obj, 'title': value}))
   }
}

I want to update something like this instead:

const onChangeCallBack(field, value){
   setObj(obj => ({...obj, field: value})) // This doesn't work
   setObj(obj => ({...obj, {field}: value})) // This doesn't work either
}

So is there a way to specify that the field is a variable to take it's value as the variable name?

CodePudding user response:

setObj(obj => ({...obj, [field]: value}))

Use square brackets to use dynamic keys.

CodePudding user response:

You need to wrap dynamic keys with square braquets like so:

{ [myDynamicKey]: value }

More on the subject here: Creating object with dynamic keys

  • Related