3

I will like to not bring back or delete the first record in the array and append it to my page. I'm getting data from a JSON file below:

$(data.content).each(function(index, content){
  $("#htmlID").append('<span>' + content.myinfo + ');
});
    {

    "content": 

    [ 
{"myinfo":"Bill Clinton 095 years old. "},
{"myinfo":"Bill Clinton 195 years old. "},
{"myinfo":"Bill Clinton 295 years old. "},
{"myinfo":"Bill Clinton 295 years old. "}

    ]
    }

When i append my data to the page everything comes out perfect, but i will like to skip the first element (index)... i basically do not want to bring back Bill Clinton 095 years old for a particular output.

How do i do that? ( grep?, remove, delete? ).

What's the simplest approach?

4 Answers 4

7

You probably don't want to modify the array or JSON, so just test which element you're on when you perform the loop:

$(data.content).each(function(index, content){
    if (index>0) { // skips first element
        $("#htmlID").append('<span>' + content.myinfo + '</span>');
    }
});

Or better yet, just use an old-fashioned for loop and save yourself some overhead:

for (var i=1; i<data.content.length; i++) {
    $("#htmlID").append('<span>' + data.content[i].myinfo + '</span>');
}
Sign up to request clarification or add additional context in comments.

1 Comment

This was my first instinct as well. Simple and it works. Certainly use the for loop even if you "like" jQuery's .each() function; that way you're not running an if statement for each item. If you don't care about preserving JSON, Grigor's method is good, too.
2

If you just want to skip the first item this will do it:

$(data.content).each(function(index, content){
  if (index > 0) {
    $("#htmlID").append('<span>' + content.myinfo + '</span>');
  }
});

Comments

2

use .shift(); method to do so, it will shift the first element

1 Comment

just remember that shift returns the shifted element; don't act upon what's returned by the shift but rather the remains of the original variable.
0

How about an old fashioned for loop that starts at index of 1:

var target = $("#htmlID");
for (var i = 1, len = data.content.length; i < len; i++) {
    target.append('<span>' + data.content[i].myinfo + '</span>');
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.