Search code examples
javascriptjavascript-objectsdelete-row

Deleting a row from javascript object


I have a javascript object which looks like this :-

var myObject = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"}, 

                {"id": "2", "URL": "http://shsusadhf.com", "value": "2"},

                {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];

Now , I have to delete all the rows in the object with id value 2. How can this be done ?


Solution

  • If you don't need the original array after "deleting" rows, you can use splice like this:

    http://jsfiddle.net/rmcu5/1/

    var myArray = [{"id": "1", "URL": "http://shsudhf.com", "value": "1"},
                    {"id": "2", "URL": "http://shsusadhf.com", "value": "2"},
                    {"id": "3", "URL": "http://shsudsdff.com", "value": "0"}];
    
    function removeItemsById(arr, id) {
        var i = arr.length;
        if (i) {   // (not 0)
            while (--i) {
                var cur = arr[i];
                if (cur.id == id) {
                    arr.splice(i, 1);
                }
            }
        }
    }
    
    removeItemsById(myArray, "2");
    
    console.log(JSON.stringify(myArray));
    

    It doesn't create a new array, just modifies the original in place. If you need the original array and all of its items, then use one of the other solutions that return you a modified copy of the original.