Wednesday, June 6, 2012

Logging full objects via console.log in VS 2012

If you call console.log() with an object, Visual Studio 2012 RC will output [Object], nothing more!
But I'm used to seeing its properties and its values, too, like in the Google Chrome Developer Console.

So I wrote my own function:
/**
 * Returns a human readable presentation of an object, its properties and its values.
 * @param obj The object
 * @param attr You can use this parameter in order to specify a prefix for each property
 * @return Returns a string
 *
 * @author ComFreek
 * @license Public Domain
 */
function logObject(obj, attr) {
    var str = "";
    attr = attr || "";
    for (var attrname in obj) {
        if (typeof obj[attrname] == "object") {
            str += "\n" + logObject(obj[attrname], attr + "." + attrname) + "\n";
        }
        else {
            str += attr + "." + attrname + "=" + obj[attrname] + "\n";
        }
    }
    return str;
}
Some sample inputs and outputs:
var obj = {
    "foo": "bar",
    "bar": "foo",

    "fooObj": {
        "barProp": "fooVal",
        "fooProp": "barVal",

        "barUnderObj": {
            "test": "test"
        }
    }
};
console.log(logObject(obj));
This outputs:
.foo=bar
.bar=foo

.fooObj.barProp=fooVal
.fooObj.fooProp=barVal

.fooObj.barUnderObj.test=test
The same code but with second argument given:
console.log( logObject(obj, "fooObj") );
Output:
fooObj.foo=bar
fooObj.bar=foo

fooObj.fooObj.barProp=fooVal
fooObj.fooObj.fooProp=barVal

fooObj.fooObj.barUnderObj.test=test

No comments:

Post a Comment