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

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

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 Relatório

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