Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit an each loop on json data in jquery ?

Tags:

json

jquery

each

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
});​
like image 289
Asimov4 Avatar asked Sep 28 '12 22:09

Asimov4


2 Answers

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.

like image 139
aquinas Avatar answered Oct 15 '22 20:10

aquinas


Try this

$.each(data.slice(0,3), function(i, item) {
    alert(item.PageName);
});​
like image 41
Sushanth -- Avatar answered Oct 15 '22 19:10

Sushanth --