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

时间:2018-10-26 10:15:09

标签: 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;
    });
}
else {
    arr.push(upload)
}

3 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:1)

const index = arr.findIndex(function(element) { return element.id === upload.id });
if (index > -1) {
    arr.splice(index, 1);
}) else {
    arr.push(upload);
}

答案 2 :(得分:0)

const toggle = (arr, obj) => arr.includes(obj) ? arr.splice(arr.indexOf(obj), 1) : arr.push(obj);