我一直在寻找一种方法,如果id变量等于对象的id,则从对象数组中删除单个对象。

我使用数组来知道选中了哪些复选框,以便收集相关信息以进行进一步处理。

例如:https://jsbin.com/vicerewevi/edit?html,js,output

快速选择复选框时出现的错误:

Uncaught TypeError: Cannot read property 'id' of undefined
    at vicerewevi.js:33
    at Function.each (jquery-3.1.0.js:368)
    at HTMLInputElement.<anonymous> (vicerewevi.js:32)
    at HTMLInputElement.dispatch (jquery-3.1.0.js:5110)
    at HTMLInputElement.elemData.handle (jquery-3.1.0.js:4918)


如果value.id == id,则在行上发生上述错误:

// if checkbox is checked, add object to array and if unchecked remove object by 'id' from array
$('.checkbox').change( function(){

    var id = parseInt($(this).attr('data-id'))
    var foo = $(this).parent().siblings().find('#foo').val()
    var bar = $(this).parent().siblings().find('#bar').val()

    if($(this).prop('checked')) {
        var obj = {'id': id, 'foo': foo, 'bar': bar}
        jsonobjects.push(obj)
    } else {
        $.each(jsonobjects, function( index, value ) {
            if (value.id == id ) {
                jsonobjects.delete(index)
            }
        });
    }
    countChecked() // update count of checkboxes
    console.log(JSON.stringify(jsonobjects))
  $('#output').html(JSON.stringify(jsonobjects, null, ""))
});


我在下面尝试的SO上找到了以下代码(以前从未使用过自定义原型):

Array.prototype.delete = function(pos){
    this[pos] = undefined;
    var len = this.length - 1;
    for(var a = pos;a < this.length - 1;a++){
      this[a] = this[a+1];
    }
    this.pop();
  }

最佳答案

因为您是数组中的delete条目,所以下次您对其进行迭代时,对于该数组中的特定“间隙”,您将得到一个value。显然,它没有undefined属性。

要解决此问题,请不要使用id,而应使用delete创建一个新的,经过过滤的数组,该数组将不会出现这种间隙。

更换:

    $.each(jsonobjects, function( index, value ) {
        if (value.id == id ) {
            jsonobjects.delete(index)
        }
    });


...具有:

    jsonobjects = jsonobjects.filter(function( value ) {
        return value.id !== id;
    });


或者,如果您要坚持使用jQuery方法,请使用filter

    jsonobjects = $.grep(jsonobjects, function( value ) {
        return value.id !== id;
    });

07-24 09:50
查看更多