Deleteing JSON object from an array creates “undefined” objects-Record and share programming errors

i am haveing some problems with JSON and arrays. I have been messing around with JSON for a little while and am trying to use some in production by refactoring a old implementation. What i had was two hidden textfields, one store ids in the format [1][2][3] etc and the other name [name1][name2][name3] so i thought this would be a great excercise to learn more about JSON and refactor that out and use a more readable object notation.

Anyway i digress. The problem i am having is a funny one, i found out how to “push” JSON into an array, but the problem comes in my delete method. When i delete an object out of the array the commas persist, creating “undefined” objects. Am i doing this wrong, and is there a better way?

Added 2 items to array (all fine)

[{id:"1", name:"Test (ID: 1)", status:"new"}, {id:"2", name:"Test 2 (ID: 2)", status:"new"}]

Removed 1 item from array (commas are left in)

[{id:"1", name:"Test (ID: 1)", status:"new"}, ,]

Added another item back into array, commas now cause “undefined” objects

[{id:"1", name:"Test (ID: 1)", status:"new"}, , {id:"2", name:"Test 2 (ID: 2)", status:"new"}]

Here is my delete function

    function removeFromList(Id) {
    var txtIDs = $("#");
    var data = eval(txtIDs.val());

    for (var i = 0; i < data.length; i++) {
        alert(typeof (data[i]));
        if (typeof(data[i]) != 'undefined') {
            if (data[i].id == Id)
                delete data[i]; // alert(data[i].name); //  
        }
    }     
}

Thanks for looking at this for me 🙂

Rob

  1. Delete is an operator used to delete keys from objects – you shouldn’t really use it to remove items from an Array because it won’t do what you expect. You can use Array methods like splice or slice to manipulate the array.

    The MDC Array methods documentation will be helpful 🙂

    Alternatively, you could use a function like this:

    function removeArrayEl(arr, index){
        newArr = [];
        for(var i = 0, l = arr.length;i < l; i++){
            if(i != index){
                newArr.push(arr[i]);
            }
        }
        return newArr;
    }
    

    [edit] As the commenters have pointed out, the Array splice method is exactly the right tool for this job, but I’ll leave the function for reference. [/edit]

Originally posted 2013-08-31 06:55:35.