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

167
Vistas
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 Respuestas
Responde la pregunta

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