Home » jQuery

jQuery: Print array and object

22 January 2010 Share/Bookmark

It’s very easy to print array and object with jQuery. You can do it with jQuery.each() function. The 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>

Cheers,

From Mukesh Chapagain's Blog, post jQuery: Print array and object

email

php magento mukesh chapagain

Get New Post by Email
RSS Feed Subscribe RSS Feed
  • http://www.rhymeswithmilk.com rhymeswithmilk

    This is fantastic, I use these bits of code all the time. I just wanted to say thanks for the help!

  • http://www.techgaun.com Samar

    Its useful. Thanks