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

171
Vistas
How to change all array while updating one element in javascript?

I need to have always only one element true in array.

Supposed I have an array

let data = [
  { letter: "a", id: 1, bool: false },
  { letter: "b", id: 2, bool: false },
  { letter: "c", id: 3, bool: false},
  { letter: "d", id: 4, bool: false },
];

every time I click on an element I need to change it to true while all other to false. I have a function

const updatedArray = data.map((item) => {
  if (item.id === id) {
    return {
      ...item,
      bool: true,
    };
  }
  return item;
});

But it works as a toggle for clicked element.

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Your problem is here: return item;,you are actually returning the previous value and just updating the bool property of item which has the same id as id variable, but you need to toggle the bool property of all the items, you can acheive your goal like this:

const updatedArray = array.map((item) => ({...item, bool: item.id === id}));
about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to also set the item's bool to false if it is not the selected item, not just set the selected item's bool to true. This should work:

const id = 3 (clicked item)
const updatedArray = array.map(item => {
  if (item.id === id) {
    return {
      ...item,
      bool: true
    };
  }
  return {
    ...item,
    bool: false
  }
});
about 4 years ago · Juan Pablo Isaza 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