Is there a nice way to loop on only the first 3 items of a json object using the jquery each loop?
I am thinking of an equivalent of the .slice(start,end) function.
var data = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "ee"},
{"Id": 10089, "PageName": "dd"},
{"Id": 10095, "PageName": "hh"}
];
$.each(data, function(i, item) {
alert(item.PageName);
// somehow break at item 3
});
var data = [
{"Id": 10004, "PageName": "club"},
{"Id": 10040, "PageName": "qaz"},
{"Id": 10059, "PageName": "ee"},
{"Id": 10089, "PageName": "dd"},
{"Id": 10095, "PageName": "hh"}
];
$.each(data, function(i, item) {
alert(item.PageName);
return i<2;
});
each stops when you return false.
From the docs:
We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.
Try this
$.each(data.slice(0,3), function(i, item) {
alert(item.PageName);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With