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

223
Vistas
Using immutability-helper in React to set variable object key

I have a function I want to write in React. In my class I have a state object fields that looks like this:

this.state = {
  step: 1,
  fields: {
    type: '',
    name: '',
    subtype: '',
    team: '',
    agreement: ''
  }
};

I have various functions that assign those keys using immutability helper that generally look like:

assignType(attribute) {
  var temp = update(this.state.fields, {
    type: {$set: attribute}
  });

  this.setState({
    fields: temp
  });
}

What I would like to do is use a function that's more generic and do something like this:

assignAttribute(field, attribute) {
  var temp = update(this.state.fields, {
    field: {$set: attribute}
  });

  this.setState({
    fields: temp
  });
}

But, this doesn't work. What can I do to use a variable key using immutability-helper?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Figured it out! I needed to use ES6 computed property names and simply edit assignAttribute to:

assignAttribute(field, attribute) {
  var temp = update(this.state.fields, {
    [field]: {$set: attribute}
  });

  this.setState({
    fields: temp
  });
}
over 4 years ago · Santiago Trujillo Denunciar

0

You can use the [] syntax if you have dynamic field names:

var data = {}
data[field] = {$set: attribute}

var temp = update(this.state.fields, data)

This gets a lot more concise if you can use ES6.

over 4 years ago · Santiago Trujillo 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