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

时间:2019-07-03 14:31:50

标签: javascript

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

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"}]

1 个答案:

答案 0 :(得分:2)

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

为此,我将使用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;
}