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

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

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 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