简体   繁体   中英

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:

在此处输入图片说明

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> 

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() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM