1

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

4
  • 3
    can you share the output json and what you want to delete from it? Commented Mar 31, 2016 at 10:16
  • 1
    couldn't see where you're using splice method... Commented Mar 31, 2016 at 10:18
  • here is my array how looks like link I'd like to delete element with index 0 Commented Mar 31, 2016 at 10:21
  • @Christian which part do you want to remove? Commented Mar 31, 2016 at 10:28

2 Answers 2

2

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>

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

Comments

2

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

1 Comment

Pleasure. Tick as correct if it answers your question :)

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.