0

Why is there an undefined in the array? How do I delete the object?

arr = [
  {id:1,name:'aaa'},
  {id:2,name:'bbb'},
  {id:3,name:'ccc'}
];

for(var item in arr){
  if(arr.hasOwnProperty(item)){
    if(arr[item].id === 2){
      delete(arr[item]);
      continue;
    }
  }
}

console.log(arr);
XiaoHu
  • 57
  • 1
  • 8

3 Answers3

2

Hope this is what you are trying to do:-

var arr = [
  {id:1,name:'aaa'},
  {id:2,name:'bbb'},
  {id:3,name:'ccc'}
];


arr = arr.filter(function(item){
  return item.id != 2;
});

console.log(arr)
Gaurav joshi
  • 1,743
  • 1
  • 14
  • 28
1

Because delete don't arranges the indexes. From the documentation

When you delete an array element, the array length is not affected. This holds even if you delete the last element of the array

For removing you need to use Array#splice function, which removes by index. Find first the index using Array#findIndex and then pass to the splice function.

arr = [
  {id:1,name:'aaa'},
  {id:2,name:'bbb'},
  {id:3,name:'ccc'}
];

const index = arr.findIndex(item => item.id === 2);
arr.splice(index, 1);
console.log(arr);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
0

You need to modify the arr which is array of objects.The delete operator removes a given property from an object, in your case you need to shift the elements after removing the object

var arr = [{
    id: 1,
    name: 'aaa'
  },
  {
    id: 2,
    name: 'bbb'
  },
  {
    id: 3,
    name: 'ccc'
  }
];
// iterating the object
arr.forEach(function(item, index) {
  //checking if id === 2, if it is 2 using splice 
//method to remove element from that index, & shift by one element
  if (item.id === 2) {
    arr.splice(index, 1)
  }
})

console.log(arr);
brk
  • 48,835
  • 10
  • 56
  • 78