Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery remove item from serialized array

I'm trying to figure out how to remove item from serializedArray by using the index. The following scenario:

[ 
    { 'name' : 'item1', 'value' : '1' }, 
    { 'name' : 'item2', 'value' : '2' }, 
    { 'name' : 'item3', 'value' : 3 } 
]

Now I would like to remove 'item2' - I can use the following function - but not sure how to remove it - is there some sort of unset() method or something like this:?

serializeRemove : function(thisArray, thisName) {
    "use strict";
    $.each(thisArray, function(index, item) {
        if (item.name == thisName) {
            // what to do here ?        
        }
    });
}
like image 381
Spencer Mark Avatar asked Dec 03 '12 16:12

Spencer Mark


Video Answer


2 Answers

You could use vanilla JS' filter() method like this:

serializeRemove : function(thisArray, thisName) {
    "use strict";
    return thisArray.filter( function( item ) {
               return item.name != thisName;
           });
}

filter() uses the callback function to test each element of the array. If the function returns true the element will be in the result. If it returns false, the element will be dropped.

filter() is supported by all major browsers and IE9+.

like image 193
Sirko Avatar answered Nov 15 '22 21:11

Sirko


You can use delete which is a standard JavaScript operator: http://jsfiddle.net/2NsUD/

var array = [ 
    { 'name' : 'item1', 'value' : '1' }, 
    { 'name' : 'item2', 'value' : '2' }, 
    { 'name' : 'item3', 'value' : 3 } 
];

var arrayClean = function(thisArray, thisName) {
    "use strict";
    $.each(thisArray, function(index, item) {
        if (item.name == thisName) {
            delete thisArray[index];      
        }
    });
}

console.log(array);
arrayClean(array, 'item3');
console.log(array);​
like image 29
Cymen Avatar answered Nov 15 '22 20:11

Cymen