dump array/object contents


/ Published in: JavaScript
Save to your folder(s)

javascript version of php print_r()
alert(dump(obj));


Copy this code and paste it in your HTML
  1. /**
  2.  * Function : dump()
  3.  * Arguments: The data - array,hash(associative array),object
  4.  * The level - OPTIONAL
  5.  * Returns : The textual representation of the array.
  6.  * This function was inspired by the print_r function of PHP.
  7.  * This will accept some data as the argument and return a
  8.  * text that will be a more readable version of the
  9.  * array/hash/object that is given.
  10.  * Docs: http://www.openjs.com/scripts/others/dump_function_php_print_r.php
  11.  */
  12. function dump(arr,level) {
  13. var dumped_text = "";
  14. if(!level) level = 0;
  15.  
  16. //The padding given at the beginning of the line.
  17. var level_padding = "";
  18. for(var j=0;j<level+1;j++) level_padding += " ";
  19.  
  20. if(typeof(arr) == 'object') { //Array/Hashes/Objects
  21. for(var item in arr) {
  22. var value = arr[item];
  23.  
  24. if(typeof(value) == 'object') { //If it is an array,
  25. dumped_text += level_padding + "'" + item + "' ...\n";
  26. dumped_text += dump(value,level+1);
  27. } else {
  28. dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
  29. }
  30. }
  31. } else { //Stings/Chars/Numbers etc.
  32. dumped_text = "===>"+arr+"<===("+typeof(arr)+")";
  33. }
  34. return dumped_text;
  35. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.