Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

104
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda