Removing a JSON object from an array creates undefined objects

I'm having some problems with JSON and arrays. I've been messing around with JSON for a while, and I'm trying to use some in production by refactoring an old implementation. I had two hidden text fields, one store identifier in the format [1] [2] [3] etc., and the other name [name1] [name2] [name3], so I thought that would be a great exercise to learn more about JSON and refactoring, which uses and uses more readable object notation.

In any case, I'm distracted. The problem I am facing is funny, I learned how to "push" JSON into an array, but the problem arises in my delete method. When I remove an object from the array, the commas are saved, creating objects "undefined". Am I doing it wrong and is there a better way?

Added 2 elements to the array (everything is fine)

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

Removed 1 element from the array (commas remain)

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

Another element added to the array, now commas call 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

+3
json javascript
May 26 '10 at 10:42
source share
1 answer

Delete is an operator used to remove keys from objects - you should not use it to remove elements from an array, because it will not do what you expect. You can use Array methods, such as splicing or slicing, to manipulate an array.

The MDC Array documentation will be helpful :)

Alternatively, you can use this function:

 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 commentators noted, the Array splice method is exactly the tool that is suitable for this job, but I left the function for reference. [/ Edit]

0
May 26 '10 at 11:01
source share



All Articles