Warm tip: This article is reproduced from stackoverflow.com, please click
javascript

How to check if an object is in array and if exist to remove it otherwise to add it?

发布于 2020-03-27 10:23:24

I am trying to find a way to check my array and add or remove objects based on name criteria.

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

var newObject =  {name: "pet"}

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

console.log(updatedArray)

I am expecting to remove the object and my updatedArray to look like [{name: "animals"}]

Questioner
Markus Hayner
Viewed
16
T.J. Crowder 2019-07-03 22:37

Your existing code will just remove it if it's there. It doesn't try to remember whether it was found and add it if it isn't.

To do that, I'd use 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 calls a callback for each array entry until the callback returns a truthy value, then stops and returns that index; if the callback never returns a truthy value, findIndex reutrns -1 when it runs out of entries.

Live Copy:

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