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

312
Visualizações
how to update an object in array if exists , other wise add it as a new object in the array in javascript?

I have an array of objects

const target = [{name: 'srk@gmail.com', selected: false, alertType: 'max'},
{name: 'abc@gmail.com', selected: true, alertType: 'clear'},]

now i want to update the array based on name and alertType. for ex: if name and alertType matches then update the selected property. if that doesn't match add a new Object. new Object is

 const = {name: 'srk@gmail.com', selected: false, alertType: 'both'}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can use Array.find() to find any matching items. You'd then update if an existing item has been found, or add a new one if not:

const target = [
  {name: 'srk@gmail.com', selected: false, alertType: 'max'},
  {name: 'abc@gmail.com', selected: true, alertType: 'clear'}
];

const update = { name: 'srk@gmail.com', selected: false, alertType: 'both' };

function updateAlerts(input, update) {
    let foundAlert = input.find(alert => ((alert.alertType === update.alertType) && (alert.name === update.name)));
    if (foundAlert) {
        foundAlert.selected = update.selected;
    } else {
        input.push(update);
    }
}

updateAlerts(target,  { name: 'srk@gmail.com', selected: false, alertType: 'both' })
console.log(target);
updateAlerts(target,  { name: 'srk@gmail.com', selected: true, alertType: 'max' })
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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