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

166
Views
how to toggle an array of objects using react useState hook

In my react app, I have multiple categories, under each categories I have multiple options. I am trying to write a function to handle toggling the selections. for example:

const initialState=[{id: "fruit", items:["apple", "banana"]}, {id: "veggie", items:["cucumber"]}]
const [selectedItems, setSelectedItems] =useState(initialState)

If I click the banana, the result should be:

[{id: "fruit", items:["apple"]}, {id: "veggie", items:["cucumber"]}]

If I click another fruit, for example, peach, the result should be:

[{id: "fruit", items:["apple", "banana", "peach"]}, {id: "veggie", items:["cucumber"]}]

If I click chicken, the result should be:

[{id: "fruit", items:["apple", "banana"]}, {id: "veggie", items:["cucumber"]}, {id: "meat", items: ["chicken"]}]

I have a toggle handler like this:

function toggle(changed: string, id: string) {
    if (selectedItems.find((cat) => cat.id === id)) {
      //toggle
    } else {
      setSelectedItems([
        ...selectedItems,
        { id: id, items: [changed] },
      ])
    }
  }

I am struggling at the toggle part to handle the existing objects. Any help? Thanks.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

function toggle(changed: string, id: string) {
if (selectedItems.find((cat) => cat.id === id)) {

  const obj = selectedItems.find(x => x.id === id);
  const itemsToProcess = obj.items

  // exist, to remove
  if(itemsToProcess.find(x => x === changed)){
      setSelectedItems([
        // things we don't touch
        ...selectedItems.filter(x => x.id !== id),
        // filtered array 
        {id, items: [...itemsToProcess.filter(i => i !== changed)]}
  ])
  }
  // to add
  else{
    setSelectedItems([
        ...selectedItems.filter(x => x.id !== id),
        {id, items: [...itemsToProcess, changed]}
    ])
  }
} else {
  setSelectedItems([
    ...selectedItems,
    { id: id, items: [changed] },
  ])
}

}

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