jQuery: Print array and object

This article shows how to print array and object on jQuery. You can do it with jQuery.each() function.

jQuery.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array.

Here is the javascript code to print array or object:


jQuery(document).ready(function(){				
	var arr = [ "earth", "mars", "jupiter", "saturn", "venus" ];
	var obj = { one:"earth", two:"mars", three:"jupiter", four:"saturn", five:"venus" };
	
	jQuery.each(arr, function(i, val) {
	  $("#arrData").append(i + " : " + val + "<br/>");		  
	});
	
	jQuery.each(obj, function(i, val) {
	  $("#objData").append(i + " => " + val + "<br/>");
	});
});

Here, arr is a numeric array. Its key and value are printed in the div with id arrData. Similarly, obj is an associative array or object. Its key and value are printed in the div with id objData.

Here is the full source code:


<html>
<head>
<title>jQuery: Print array and object</title>
<script src="jquery-1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
	jQuery(document).ready(function(){				
		var arr = [ "earth", "mars", "jupiter", "saturn", "venus" ];
		var obj = { one:"earth", two:"mars", three:"jupiter", four:"saturn", five:"venus" };
		
		jQuery.each(arr, function(i, val) {
		  $("#arrData").append(i + " : " + val + "<br/>");		  
		});
		
		jQuery.each(obj, function(i, val) {
		  $("#objData").append(i + " => " + val + "<br/>");
		});
	});
</script>
</head>
<body>
<div id="arrData">
<strong>Array</strong><br/>

</div>

<div id="objData">
<strong>Object</strong><br/>

</div>
</body>
</html>

Thanks.