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

137
Vistas
Using Dynamic Value to add Object to Array with the Spread Operator

I have some code within a function that looks like this:

 const updatedItemsArr = [...this.state.targetItems, {relationship: value}];

What I want to do is pass in a dynamic value in place of relationship. However, whatever I try ends up causing an error or is incorrect syntax.

This will not work:

const fieldType = 'relationship';
const updatedItemsArr = [...this.state.targetItems, {fieldType: value}];

Nor will this:

  const updatedItemsArr = [...this.state.targetItems, {`${fieldType}`: value}];

How can I pass in a dynamic value here?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

In ES6 what you can do is you can put the dynamic key inside brackets. So

const updatedItemsArr = [...this.state.targetItems, {[fieldType]: value}];

should work.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Something like this should do the trick.

const dynObj = {};
dynObj[fieldType] = value;  
const updatedItemsArr = [...this.state.targetItems, dynObj];
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