温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - How to check if an object is in array and if exist to remove it otherwise to add it?

javascript - 如何检查对象是否在数组中以及是否存在以删除它,否则添加它?

发布于 2020-03-27 11:14:35

我想找到一种方法来检查我的数组,并根据名称标准添加或删除对象。

var array = [{name: "pet"}, {name: "animals"}]

var newObject =  {name: "pet"}

var updatedArray = array.filter(el => el.name !== newObject.name)

console.log(updatedArray)

我希望删除该对象和我的UpdatedArray看起来像 [{name: "animals"}]

查看更多

查看更多

提问者
Markus Hayner
被浏览
9
T.J. Crowder 2019-07-03 22:37

如果现有代码存在,则将其删除。它不会尝试记住是否已找到它,如果找不到则添加它。

为此,我将使用findIndex

function removeOrAdd(array, obj) {
    var index = array.findIndex(el => el.name === newObject.name)
    if (index === -1) {
        // Not found, add it
        array.push(newObject);
    } else {
        // Found, remove it
        array.splice(index, 1);
        // or create a new array instead of splicing:
        //array = array.filter(function(_, i) { return i !== index);
    }
}

findIndex为每个数组项调用一个回调,直到该回调返回真实值,然后停止并返回该索引;如果回调函数从不返回真实值,findIndex则在条目用尽时返回-1。

实时复制:

function removeOrAdd(array, obj) {
    var index = array.findIndex(el => el.name === newObject.name)
    if (index === -1) {
        // Not found, add it
        array.push(newObject);
    } else {
        // Found, remove it
        array.splice(index, 1);
        // or create a new array instead of splicing:
        //array = array.filter(function(_, i) { return i !== index);
    }
}

var array = [{name: "pet"}, {name: "animals"}]
var newObject =  {name: "pet"}

console.log("before", array);
removeOrAdd(array, newObject); // Found, so it was removed
console.log("after1", array);
removeOrAdd(array, newObject); // Not found, so it was added
console.log("after2", array);
.as-console-wrapper {
    max-height: 100% !important;
}

发布
问题

分享
好友

手机
浏览

扫码手机浏览