Home » jQuery

jQuery: Print array and object

22 January 2010 12,303 views Popularity: 42% Share/Bookmark

email

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,

Related posts:

  1. print_r in Javascript
  2. jQuery: Grey out background and preview image as popup
  3. Magento jQuery: How to use them together?
  4. jQuery: How to replace string, div content and image src?
  5. Using jQuery & AJAX: Populate Selection List
  6. jQuery: Preview Image with Tooltip Effect
  7. jQuery: Preview Image with Zoom Effect
  8. jQuery: A simple Slideshow
  9. jQuery: Animate and Transfer effect with Image
  10. jQuery: Set time interval between events with queue function
  • 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