views:

39

answers:

1

Hi All,

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 = $("#<%= selected.ClientID %>");
    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

A: 

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]

adamnfish
Have you ever heard of Array.slice? It's a native function that is used to remove elements from an array.
CharlesLeaf
Using the `splice` method would certainly be easier.
Gumbo
You say "there isn't a cross browser function for 'removing a single array element from the middle of an Array re-indexing the remaining elements'". Yes there is, and you mentioned it: `splice`. For example: `var a = ["a", "b", "c"]; a.splice(1, 1);` will remove the item at position 1 ("b") from the array.
Tim Down
splice did the trick, thank you guys!!!
Modika