[javascript] dump an arbitrary object

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

[javascript] dump an arbitrary object

Post by Weirdan »

Code: Select all

/**
Copyright (c) 2005, Bruce Weirdan <weirdan@gmail.com>
All rights reserved.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * Neither the name of the author nor the names of his contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**/
function dump(o, level) {
   level = level || 0;
   if(level>dump.maxLevel) return "Too deep";
   if(level || (dbg = document.getElementById('dbg_win'))) {
      var ret = '';

      if(typeof(o) != 'function')
         ret = typeof(o) + ': ';

      if(typeof(o) == 'object') {
         ret+= '\r\n';
         try {
            for(i in o) {
               try {
                  ret += "\t".repeat(level) + i + ' => ' + dump(o[i], level+1) + '\r\n';
               } catch(e) {}
            }
         } catch(e) {
            ret = 'can\'t iterate over object';
         }
      } else {
         try {
            ret += o.toString().indent(level, 1);
         } catch(e) {
            ret += 'can\'t convert to string';
         }
      }
      if(level) {
         return ret;
      } else {
         dbg.appendChild(document.createTextNode(ret));
         dbg.appendChild(document.createElement('hr'));
      }
   }
}

dump.maxLevel = 4;
if(!String.prototype.repeat) {
   String.prototype.repeat = function(n) {
      var s=this.toString(), ret='';
      while( (n--) > 0) ret+=s;
      return ret;
   }
}
if(!String.prototype.indent) {
   String.prototype.indent = function(level, dontIndentFirst, indentChar) {
      indentChar = indentChar || "\t";
      dontIndentFirst = Number(dontIndentFirst)||0;
      var s = this.toString();
      s = s.split(/^/m);
      for(var i=dontIndentFirst, l=s.length; i<l; i++)
         s[i] = indentChar.repeat(level) + s[i];
      return s.join("");
   }
}
Intent
In the lack of decent js debugger I was trying to mimic the var_dump function.

Usage
Suppose you have this function stored in js/dump.js in the document root of your server. To use it on your page you would include the following bits:

Code: Select all

<script type='text/javascript' src='js/dump.js'></script>
..........
<!-- somewhere in the <body> element -->
<pre id='dbg_win' style='border: red dashed 1px; text-align:left'></pre> 
and to actually use:

Code: Select all

<script type='text/javascript'>
function exampleObj() {
  this.something = 'blah';
  this.anotherVar = ['array', 'example'];
  this.objectVar = {innerObjVar: 123, anotherInnerObjVar='String example'};
  this.domVar = document.getElementById('dbg_win');
}

var example = new exampleObj();

dump(example);
</script> 
Voila. example variable has been dumped to the 'dbg_win' DOM element.

Notes
  • You can dump any variable, including DOM parts. dump(document.implementation) for example.
  • Actually I don't include 'dbg_win' element in the page source. Instead I have three bookmarklets in my browser: Enable debug, Clear debug window and Disable debug. Here they are (every bookmark should be prefixed with javascript: scheme):

    Code: Select all

    // Enable Debug
    if(!document.getElementById('dbg_win')) { var elt = document.createElement('pre'); elt.style.border='red dashed 1px'; elt.style.textAlign='left'; elt.id='dbg_win'; var body = document.getElementsByTagName('body')[0]; if(body) void(body.insertBefore(elt, body.firstChild)); if(window.ondebugenable) window.ondebugenable();}
    
    // Disable debug
    var elt; if(elt = document.getElementById('dbg_win')) void(elt.parentNode.removeChild(elt));
    
    // Clear debug window
    var elt; if(elt=document.getElementById('dbg_win')) void(elt.innerHTML='');
    
Post Reply