【问题标题】:how to update an object in array if exists , other wise add it as a new object in the array in javascript?如果存在,如何更新数组中的对象,否则将其作为新对象添加到 javascript 中的数组中?
【发布时间】:2021-10-13 13:07:21
【问题描述】:

我有一个对象数组

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

现在我想根据名称和警报类型更新数组。 例如:如果 name 和 alertType 匹配,则更新选定的属性。 如果不匹配添加一个新对象。 新对象是

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

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

您可以使用Array.find() 查找任何匹配项。如果找到现有项目,您将更新,如果没有,则添加新项目:

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

【讨论】:

    猜你喜欢
    • 2014-05-15
    • 2019-09-15
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    相关资源
    最近更新 更多