Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!