Looping Through JSON & Wrapping Subsets with JQuery
So, you have just received JSON data via an AJAX request and you need to loop through, what is effectively an associative array, wrapping every few generated html records in a wider tag set, creating record subsets and allowing you to generate the requisite code for a slider or pager. How do you go about acheiving this?
The request for JSON in JQuery will look something like this:
$.ajax({
type: "POST",
url: "/your-url.com",
dataType: "json",
success: function(data) {
...
}
});
Within the success response handler function you will then want to do the requisite looping and wrapping accordingly, by whatever means is favored, be it using custom object functions or otherwise. By way of example you might use the following code:
//clear out the existing results
$("#results").empty();
//initialize counters
var counter = 0;
var setcounter = 0;
var numberSubset = 6;
//iterate through JSON array
for(item in data) {
//assign this object to a var
var project = data[item];
//add project details to results
$("#results").append('<div id="'+ project.id +
'" class="resultitem"> ... </div>');
//add new results group set
var resultitems = $('#results > .resultitem');
if ($(resultitems).size() == numberSubset) {
//wrap current resulitems in resultgroup
$(resultitems).wrapAll('<div id="set-' +
setcounter +'" class="resultgroup"></div>');
//increment set number counter
setcounter++;
}
//increment record counter
counter++;
}
//catch residual resultitems and wrap in resultgroup
$('#results > .resultitem').wrapAll('<div id="set-' +
setcounter +'" class="resultgroup"></div>');
And there you have it, a quick and easy way to loop through a JSON array, creating subsets of records in the html output using JQuery.


















August 12th, 2010 at 4:30 pm
Seriously? Come on guys, the most basic variable name check would show this couldn’t possibly work. it requires that you get the value from ‘data[item]‘, what is ‘list[item]‘???
And you forgot the prototype property wrapper. The loop should be wrapped to skip inherited possibles and using the proper variable names…
for(item in data) {
// skip inherited properties
if (data.hasOwnProperty(item)) {
//assign this object to a var
var project = data[item];
…
}
}
You should use the jquery shortcuts or at least DOM calls for creating elements instead of inserting html strings, its no wonder bad style pukes out of amateurs when their examples are this awful.