5

I have this array of objects and i would like to delete the last object. i.e. 2 from the list. Can someone please let me know to do this.

Object {Results:Array[3]}
Results:Array[3]
[0-2]
  0:Object
         id=1     
         name: "Rick"
         Value: "34343"
  1:Object
         id=2     
         name:'david'
         Value: "2332"
  2:Object
         id=3
         name: 'Rio'
         Value: "2333"
Akanksha Iyer
  • 129
  • 2
  • 4
  • 7

5 Answers5

10

Try using the .pop() method. It'll delete the last item of an array.

obj.Results.pop();
baranskistad
  • 2,176
  • 1
  • 21
  • 42
Robiseb
  • 1,576
  • 2
  • 14
  • 17
6

You could just splice out the last element in the array:

obj.Results.splice(-1);

var obj = {
  Results: [{
    id: 1,   
    name: "Rick",
    Value: "34343"
  }, {
    id:2,
    name: 'david',
    Value: "2332",
  }, {
    id: 3,
    name: 'Rio',
    Value: "2333"
  }]
};

obj.Results.splice(-1);
console.log(obj);
Tholle
  • 108,070
  • 19
  • 198
  • 189
3

You can pop() the last item out of the array.

obj.Results.pop()

For more on array methods, visit this.

baranskistad
  • 2,176
  • 1
  • 21
  • 42
2

You can use Array.prototype.splice to remove the last item.

var data = {
  Results : [ {
    id    : 1,  
    name  : "Rick",
    Value : "34343"
  }, {
    id    : 2,
    name  :'david',
    Value : "2332"
  }, {
    id    : 3,
    name  : 'Rio',
    Value : "2333"
  }]
};

var removed = data.Results.splice(-1,1);

document.body.innerHTML = '<pre>'+ JSON.stringify(data, null, 4) +'</pre>'
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
2

You should use array.pop() for it, it removes the last element and returns it.

Code Spirit
  • 3,992
  • 4
  • 23
  • 34