When you use delete on array element, it is replaced by undefined. Correct way to delete element from array is to use array.splice()
Delete
var obj = [{
player_id: 1,
team_id: 2
}, {
player_id: 2,
team_id: 2
}, {
player_id: 3,
team_id: 1
}, {
player_id: 4,
team_id: 1
}]
var value = 4;
for (var key in obj) {
if (obj[key].player_id === value) {
delete obj[key];
break;
}
}
console.log(obj)
Array.splice
var obj = [{
player_id: 1,
team_id: 2
}, {
player_id: 2,
team_id: 2
}, {
player_id: 3,
team_id: 1
}, {
player_id: 4,
team_id: 1
}]
var value = 4;
for (var i =0; i< obj.length; i++) {
if (obj[i].player_id === value) {
obj.splice(i,1)
break;
}
}
console.log(obj)
Also, for..in is for objects. You should use for or any other array function to loop over arrays.
Array.findIndex
var obj = [{
player_id: 1,
team_id: 2
}, {
player_id: 2,
team_id: 2
}, {
player_id: 3,
team_id: 1
}, {
player_id: 4,
team_id: 1
}]
var value = 4;
var index = obj.findIndex(x=>x.player_id === value);
obj.splice(index,1)
console.log(obj)
Note: array.findIndex is a part of ES6 and will have compatibility issue. Please refer them before using.
objis an array. Usesplice(index, 1)array.findIndex()