Javascript 如果对象在JS中的数组中,则从数组中推送或移除对象

Javascript 如果对象在JS中的数组中,则从数组中推送或移除对象,javascript,Javascript,我正在寻找更优雅、更高效的方法来切换数组中的对象 因此,我的arr是: let arr = [ {id: 2}, {id: 3}, ... ] 现在我这样做: if (arr.find(function(element) { return element.id === upload.id } )) { arr = arr.filter(function(element) { return element.id !== upload.id; }

我正在寻找更优雅、更高效的方法来切换数组中的对象

因此,我的arr是:

let arr = [
   {id: 2},
   {id: 3},
   ...
] 
现在我这样做:

if (arr.find(function(element) { return element.id === upload.id } )) {
    arr = arr.filter(function(element) {
        return element.id !== upload.id;
    });
}
else {
    arr.push(upload)
}

如果经常切换对象,可以使用哈希表作为数组的索引

var hash = Object.create(null);

function update(array, item) {
    if (hash[item.id] !== undefined) {
        array.slice(hash[item.id], 1);
        hash[item.id] = undefined;
    } else {
        hash[item.id] = array.push(item) - 1;
    }
}

好的,我的想法是查找查找元素的索引,如果存在,则使用splice从数组中删除项。编辑问题并添加一些有意义的注释,引导用户理解您提供的解决方案。您的选项无效,因为它不检查id。
var hash = Object.create(null);

function update(array, item) {
    if (hash[item.id] !== undefined) {
        array.slice(hash[item.id], 1);
        hash[item.id] = undefined;
    } else {
        hash[item.id] = array.push(item) - 1;
    }
}
const index = arr.findIndex(function(element) { return element.id === upload.id });
if (index > -1) {
    arr.splice(index, 1);
}) else {
    arr.push(upload);
}