I have searched for a way to remove single object from an array of objects if id variable equals the id of an object.
I use the array to know which checkboxes are selected so that related information will be collected for further processing.
example: https://jsbin.com/vicerewevi/edit?html,js,output
Error that I get when I select the checkboxes fast:
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)
above error occurs on the line if 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, ""))
});
I found this code below on SO (never worked with custom prototypes before) that I tried:
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();
}
Aucun commentaire:
Enregistrer un commentaire