0

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'}
sravan ganji
  • 4,774
  • 3
  • 25
  • 37
  • 4
    Well you will obviously have to search your array for an object that has this exact name and alertType. – CBroe Oct 13 '21 at 13:09
  • https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find –  Oct 13 '21 at 13:10
  • Does this answer your question? [Modify object property in an array of objects](https://stackoverflow.com/questions/16691833/modify-object-property-in-an-array-of-objects) – pilchard Oct 13 '21 at 13:16

1 Answers1

2

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; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40