Christian
Christian

Reputation: 655

Deleting element from array in jQuery

I'm trying to remove the first element from array which I getting from xml file. I tried to use splice method but it doesn't work. Can someone help me?

.ajax({
    type: "GET",
    url: 'my.xml',
    dataType: "xml",
    success: function(xml) {
        var array = [];
        var data = $.xml2json(xml)['#document'];
        that.array = data.contacts;
    }
})

data:

enter image description here

Upvotes: 1

Views: 86

Answers (2)

Jai
Jai

Reputation: 74738

As you have attached a screenshot of your Object data then you can use Array.prototype.shift() to remove the first entry in the array:

var array = [];
var data = $.xml2json(xml)['#document'];
array = data.contact.name.shift(); // <----this will remove the first entry in the array.

a sample demo:

var array = [];
var data = {
  contact: {
    name: [{
      name: "one"
    }, {
      name: "two"
    }, {
      name: "three"
    }]
  }
};
array = data.contact.name.shift(); // <----this will remove the first entry in the array.
document.querySelector('pre').innerHTML = JSON.stringify(data, 0, 3);
<pre></pre>

Upvotes: 2

Stuart
Stuart

Reputation: 6780

Find the index of the element you want to remove (using indexOf) and then use splice to remove it....

var idx = that.array.indexOf(theIndexyouWantToRemove);
that.array.splice(idx, 1);

If its definitely the first element always, then you could use shift().

Upvotes: 2

Related Questions