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

162
Views
¿Cómo cambiar toda la matriz mientras se actualiza un elemento en javascript?

Necesito tener siempre solo un elemento true en la matriz.

Se supone que tengo una matriz

 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 }, ];

cada vez que hago clic en un elemento, necesito cambiarlo a true mientras que todos los demás son false . tengo una funcion

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

Pero funciona como un interruptor para el elemento en el que se hizo clic.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Tu problema está aquí: return item; , en realidad está devolviendo el valor anterior y simplemente actualizando la propiedad bool del elemento que tiene la misma identificación que la variable id , pero necesita alternar la propiedad bool de todos los elementos, puede lograr su objetivo de esta manera:

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

0

También debe establecer el bool del elemento en falso si no es el elemento seleccionado, no solo establecer el bool del elemento seleccionado en verdadero. Esto debería funcionar:

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