Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

245
Views
Use a variable for object name to be changed with spread operator (Reactjs)

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

Use square brackets to use dynamic keys.

about 4 years ago · Juan Pablo Isaza Report

0

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

{ [myDynamicKey]: value }

More on the subject here: Creating object with dynamic keys

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!