Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete an item from array of objects?

    var arr = [
                     {id:2,date:'2010-10-03',des:'goodday'},
                     {id:3,date:'2011-02-13',des:'badday'},
                     {id:4,date:'2011-04-03',des:'niceday'}
                   ];

Now I want to delete {id:3,date:'2011-02-13',des:'badday'} , and then the arr should be

        var arr = [
                     {id:2,date:'2010-10-03',des:'goodday'},
                     {id:4,date:'2011-04-03',des:'niceday'}
                   ];

How should I do?

like image 917
Cynial Avatar asked Apr 12 '11 02:04

Cynial


2 Answers

Assume the id fields in you Objects are unique you can do the following to delete it. The function to use is Splice:

    var arr = [
        {
        id: 2,
        date: '2010-10-03',
        des: 'goodday'},
    {
        id: 3,
        date: '2011-02-13',
        des: 'badday'},
    {
        id: 4,
        date: '2011-04-03',
        des: 'niceday'}
    ];

    for(var i=0; i<arr.length; i++){
        if(arr[i].id == 3){
            arr.splice(i, 1);  //removes 1 element at position i 
            break;
        }
    }

console.log(arr);  
//should give you 
//                      var arr = [
//                               {id:2,date:'2010-10-03',des:'goodday'},
//                               {id:4,date:'2011-04-03',des:'niceday'}
//                          ];
like image 146
KJYe.Name Avatar answered Oct 08 '22 03:10

KJYe.Name


See here:

http://wolfram.kriesing.de/blog/index.php/2008/javascript-remove-element-from-array

like image 32
cwharris Avatar answered Oct 08 '22 02:10

cwharris