Dump object properties (recursive)


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



Copy this code and paste it in your HTML
  1. function dump(o,limit,e,clicked) {
  2. var outer = false;
  3. if (e===undefined) {
  4. dump.o=[];
  5. dump.n = function(o) { // get display name for object
  6. if (o===undefined) return '<i>undefined</i>';
  7. if (o===null) return '<i>null</i>';
  8. var c = o.constructor;
  9. return '<span style="color:#666"> <i>' + typeof o + '</i> '
  10. +(c ? String(c).split('{')[0].substr(8) :'') + '</span> '
  11. +'<pre style="display:inline">' + dump.esc(o) + '</pre>' }
  12. dump.hp = function(o) { // determine if object has props
  13. for (undefined in o) return true; return false; }
  14. dump.t = function(e,rhs) { // toggle property list viz
  15. var n = rhs ? e.previousSibling : e.nextSibling;
  16. var s = n.style;
  17. if ((!n.hasData) && s.display == 'none')
  18. return dump.load(n);
  19. n.hasData = true;
  20. s.display = s.display == 'none' ? 'block' : 'none';
  21. return false; }
  22. dump.load = function(e) { // show non-dumped item
  23. e.hasData = true;
  24. e.style.display = 'block';
  25. dump(dump.o[e.getAttribute('obj')],1,e,true);
  26. return false; }
  27. dump.esc = function(s) { // html escape
  28. return String(s).replace(/&/g,'&amp;')
  29. .replace(/</g,'&lt;').replace(/\>/g,'&gt;') }
  30. outer = true;
  31. e = document.createElement('div');
  32. e.style.font = '11px sans-serif'; }
  33. if (outer || clicked) {
  34. e.val = "";
  35. e.write = function(s) {e.val += s}
  36. e.flush = function() {e.innerHTML += e.val; e.val = ''} }
  37. if (limit===undefined) limit = 3;
  38. var tab = '<br/\><a href="#" onclick="return dump.t(this)">'
  39. +'<b>{</b></a><div style="margin-left:1em'
  40. +(limit ? '' : ';display:none') +'"'
  41. +(limit ? '' : 'obj="'+dump.o.length+'" ') +'>';
  42. var end = '</div><a href="#" onclick="return dump.t(this,1)">'
  43. +'<b>}</b></a><br/\>';
  44. if (!limit) {
  45. if (!dump.hp(o))
  46. return e.write(dump.n(o)+'<br/\>');
  47. dump.o.push(o);
  48. return e.write(dump.n(o)+tab+end); }
  49. if (!clicked) e.write(dump.n(o));
  50. var c = 0;
  51. for (var p in o) {
  52. if ((!clicked) && !c++) e.write(tab);
  53. e.write("<b>"+p+"</b> => ");
  54. dump(o[p], limit-1, e); }
  55. e.write(clicked ? "" : c ? end : "<br/\>");
  56. if (outer || clicked) e.flush();
  57. if (outer) document.body.appendChild(e); }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.