In my years of doing Web development, I’ve written this function several times over; however, I can NEVER find the code when I need it! Thus, here is a simple Javascript function to dump the contents of any object (posted to share, but also for my own permanent reference!)
var MAX_DUMP_DEPTH = 10;
function dumpObj(obj, name, indent, depth) {
if (depth > MAX_DUMP_DEPTH) {
return indent + name + ": <Maximum Depth Reached>\n";
}
if (typeof obj == "object") {
var child = null;
var output = indent + name + "\n";
indent += "\t";
for (var item in obj) {
try {
child = obj[item];
} catch (e) {
child = "<Unable to Evaluate>";
}
if (typeof child == "object") {
output += dumpObj(child, item, indent, depth + 1);
} else {
output += indent + item + ": " + child + "\n";
}
}
return output;
} else {
return obj;
}
}
This will spit out the contents of the object (and nested objects) to an indented string, which is useful when trying to inspect the contents of DOM, etc. Note that a recursive method like this can be dangerous, so I’ve included a maximum depth flag, MAX_DUMP_DEPTH, to ensure your browser doesn’t get locked up in an infinite nested loop.
Enjoy!