JavaScript object dump

I thought I posted this before, but I guess I did not.

Here’s one way to dump a JavaScript object for analysis (if you don’t have access to Firebug, or a similar tool).

Note it only dumps one level of data, and the code below is specifically for dumping an exception (catch ex), but swap ex in the three spots one spot with whatever object you’d like dumped.

var objectInfo = “”;
// Change ex to whatever object you want to debug.
var objectToDebug = ex;
for (var prop in objectToDebug) {
    objectInfo += “property: “ + prop + ” value: [” + objectToDebug[prop] + “]\n”;
}
objectInfo += “toString(): “ + ” value: [” + objectToDebug.toString() + “]”;
alert(objectInfo);

I’m almost positive I found this code (pre-modifications) somewhere, but can’t determine where that was (and having emailed myself this in December, lost my browsing history from that time). I’ve also updated the code to make use of variables, instead of the old method of adding the object to dump in a total of three spots.

And here’s a function:

function dumpObject(o) {
    var objectInfo = “”;
    var objectToDebug = o;
    for (var prop in objectToDebug) {
        objectInfo += “property: “ + prop + ” value: [” + objectToDebug[prop] + “]\n”;
    }
    objectInfo += “toString(): “ + ” value: [” + objectToDebug.toString() + “]”;
    alert(objectInfo);
}