Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

246
Vistas
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 Respuestas
Responde la pregunta

0

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

Use square brackets to use dynamic keys.

about 4 years ago · Juan Pablo Isaza Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda