Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete last object from the array of objects. [duplicate]

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"
like image 336
Akanksha Iyer Avatar asked Sep 20 '16 21:09

Akanksha Iyer


4 Answers

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

obj.Results.pop();
like image 89
Robiseb Avatar answered Sep 16 '22 23:09

Robiseb


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);
like image 42
Tholle Avatar answered Sep 16 '22 23:09

Tholle


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>'
like image 44
Mr. Polywhirl Avatar answered Sep 19 '22 23:09

Mr. Polywhirl


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

like image 21
Code Spirit Avatar answered Sep 18 '22 23:09

Code Spirit