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

105
Vistas
Accessing JavaScript Object property dynamically during useState update

I have useState variable defined as such

 const [queryBuilder, setQueryBuilder] = useState({location: [], metric: [], datetime: [], statistics: []})

then I have a function which should be able to set individual property back to empty array []. Here I ran into problem and I tried several ways but none worked, for example.

const clearCategory = (e, category) => {
    setQueryBuilder(prev => { return {...prev, prev[category]: []}})
}

this wont work, but I try to access property via previous object and bracket notation (i also tried dot notation).

Normally I can access dynamically like so

queryBuilder[category]

but during useState hook I cant, how do I accomplish this ?

And, writing

setQueryBuilder(prev => {return {...prev, category: []}})

will just create a new property named category with an empty array

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

0

What you should use here is a computed property name, which is a feature introduced in ECMAScript 2015. For your example it will look like this:

{ ...prev, [category]: [] }

Note that the computed property itself doesn't reference your prev object and it's technically unrelated to it. It's simply a unique member of the object that overwrites any property with the same name from the prev object since it's being defined after prev was spread into the object.

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