Friday, September 7, 2012

JavaScript object inspector

A JavaScript object is a collection of properties. You can think of a property as a pair (key : value).
To inspect an object in JavaScript you use the for in operator.

The following function inspects an object by looping on the properties and calling itself recursively.

var objectInspector = function recursiveObjectInspector(obj) {
    var string = '';
    for (var propName in obj) {
        if(typeof(obj[propName]) !== 'object')
            string += propName+" : "+obj[propName]+",\n";
            string += '\n'+propName+' {\n'+ recursiveObjectInspector(obj[propName])+"}\n";
    return string;