0

I have an array of objects

const target = [{name: '[email protected]', selected: false, alertType: 'max'},
{name: '[email protected]', 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: '[email protected]', selected: false, alertType: 'both'}
3

1 Answer 1

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: '[email protected]', selected: false, alertType: 'max'},
  {name: '[email protected]', selected: true, alertType: 'clear'}
];

const update = { name: '[email protected]', 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: '[email protected]', selected: false, alertType: 'both' })
console.log(target);
updateAlerts(target,  { name: '[email protected]', selected: true, alertType: 'max' })
console.log(target);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.