Search This Blog

Jun 3, 2012

jQuery: How to iterate array and object on jQuery

jQuery.each() function is a big help if you we’re into array or object iteration. It has the same concept with PHP foreach syntax when it comes to object and array iteration so if you’ll find it easy when you already learn PHP foreach.

jQuery.each( collection, callback(indexInArray, valueOfElement) )

collection - is the array or the object
callback(indexInArray, valueOfElement) - The function that will be executed on every object / array

Example: Array
We’re going to iterate and get the key and value of the given array below:
var arr1  =  [ "earth", "mars", "jupiter", "saturn", "venus" ]; 
We can alert each array value by doing:
jQuery.each(arr, function(i, val) {

 alert(‘key:’+i+ ‘ value: ’+val);
Or you can append it in your HTML DOM using the append function.
jQuery.each(arr, function(i, val) {

 $("#DOMIDSAMPLE").append(i + " : " + val + "<br/>");
Going for object is still the same concept.

Example: Object
var objs = { firstname: "John", lastname: "Doe" }; 
$.each(objs, function(k, v){
   alert( "Key: " + k + ", Value: " + v );
Important: Please take note that $(‘selector’).each() function is different to the above function. $(‘selector’).each() is use for DOM iteration.