1

Is it possible to delete an entry from a JavaScript array? The entry in the list gets replaced with null when delete operator is used.

data = [{pid:30, pname:abc}, {pid:31, pname:def}, {pid:32, pname:zxc}]
delete data[1]

becomes:

data = [{pid:30, pname:abc}, null, {pid:32, pname:zxc}]

FYI I'm getting this as json back from an ajax call. The returned value is parsed like var data = YAHOO.lang.JSON.parse(result.value || '[]')

4
  • what language are you working in? Commented Dec 16, 2009 at 16:10
  • Just to avoid confusion, JSON refers to the actual String value returned by a JSON stringifier. It looks like you are actually talking about a JavaScript literal expression, which looks like JSON but is actually JS code. Commented Dec 16, 2009 at 16:26
  • oh sorry should have mentioned its javascript. Commented Dec 16, 2009 at 16:29
  • its javascript and json is returned from an ajax call to php. the returned value is parsed like var data = YAHOO.lang.JSON.parse(result.value || '[]'); Commented Dec 16, 2009 at 16:37

3 Answers 3

1

What about sort()ing and then splice()ing the list?

Sign up to request clarification or add additional context in comments.

1 Comment

To cellect all the nulls together and splice them all at once.
1

There are many librarys out there that deal with the serialization and deserialzation of JSON content. Many of those librarys also allow you to manipulate the data from JSON also.

Depending on what language you're using will determine which library you decide to use.

More details would be helpful.

2 Comments

its javascript and json is returned from an ajax call to php. the returned value is parsed like var data = YAHOO.lang.JSON.parse(result.value || '[]');
FYI I updated the question to include the specific JavaScript context the OP is in.
0

This is a problem with the JavaScript Array class. Deleting a value always leaves a hole. You need to create a new array without the hole. Something like this might be helpful:

    Array.prototype.removeItem = function(index){
        var newArray = []
        for (var i =0; i < this.length; ++i){
            if (i==index||typeof this[i] === "undefined") continue;
            newArray.push(this[i]);
        }
        return newArray;
    }

    var a1 = [1,2,3,4,5]
    delete a1[1]
    alert(a1.join())
    //prints 1,,3,4,5

    var a2 = a1.removeItem(3)
    alert(a2.join())
    //prints 1,3,5 -- removed item 3 and previously "deleted" item 1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.