首页 > 解决方案 > 对象数组:无法读取 onchange 事件中未定义的属性“id”

问题描述

如果 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();
  }

标签: javascriptjqueryarrayscheckbox

解决方案


因为您delete从数组中输入,所以下次迭代它时,您将得到一个value用于undefined数组中特定“间隙”的值。显然,它没有id属性。

为了解决这个问题,不要使用delete,而是使用filter创建一个新的过滤数组,它不会有这样的间隙。

代替:

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

...和:

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

或者,如果您想坚持使用 jQuery 方法,请使用$.grep

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

推荐阅读