Feedback

Codebox Software

JavaScript Object Printer

Tags:  
Published: 10 Aug 2008

Modern browsers now support recursive object printing natively, via the JSON.stringify function
If possible you should use this approach instead of the one described below.

Anyone working with JavaScript who doesn't have the benefit of a browser-based debugger may find this function useful - it produces a string containing the names and values of all the properties of an object:

function print(obj, maxDepth, prefix){
   var result = '';
   if (!prefix) prefix='';
   for(var key in obj){
       if (typeof obj[key] == 'object'){
           if (maxDepth !== undefined && maxDepth <= 1){
               result += (prefix + key + '=object [max depth reached]\n');
           } else {
               result += print(obj[key], (maxDepth) ? maxDepth - 1: maxDepth, prefix + key + '.');
           }
       } else {
           result += (prefix + key + '=' + obj[key] + '\n');
       }
   }
   return result;
}

The function is recursive, so if the object contains other objects those will be printed as well - recursion will continue down to the depth specified by the 'maxDepth' argument, or indefinitely if no maxDepth is specified; array elements are also displayed. In the example below the 'myObject' object has 4 properties - a string, a number, an array, and an object:

var myObject = {
    'name' : 'rob', 'age' : 36, 
    'languages' : ['java', 'javascript', 'c#'], 
    'location' : {
        'country' : 'uk', 
        'city' : 'manchester', 
        'area' : 'chorlton'
    }
};
...
alert(print(myObject));

The 'alert' will display the following output:

name=rob
age=36
languages.0=java 
languages.1=javascript
languages.2=c#
location.country=uk
location.city=manchester
location.area=chorlton

It is also possible to replace the default 'toString' method provided by JavaScript (which would just display '[object Object]') with the print() function shown above, by using the following line:

Object.prototype.toString = function(){ return print(this) };

Send Feedback

Use this form to send feedback, if you want a reply please include your email address!