In php var_dump() provides a nice easy way to identify exactly what an object is and what it contains.
Unfortunately, there is no equivalent built-in to Javascript. But as with most programming languages, new features are just a few lines of code away:
function ObjectDump(obj, name) { this.result = "[ " + name + " ]\n"; this.indent = 0; this.dumpLayer = function(obj) { this.indent += 2; for (var i in obj) { if(typeof(obj[i]) == "object") { this.result += "\n" + " ".substring(0,this.indent) + i + ": " + "\n"; this.dumpLayer(obj[i]); } else { this.result += " ".substring(0,this.indent) + i + ": " + obj[i] + "\n"; } } this.indent -= 2; } this.showResult = function() { var pre = document.createElement('pre'); pre.innerHTML = this.result; document.body.appendChild(pre); } this.dumpLayer(obj); this.showResult(); }
The best way to use it is to put the above in a separate script (say object_dump.js
) and include it in your page. Then dumping any object is as easy as:
ObjectDump(object, "description");
The second parameter lets you label the dump in case you are dumping more than one object or using it in a loop. The output is conveniently appended to the bottom of the page so it shouldn’t interfere with your real content.
I needed this to help identify an issue buried deep in a complex array. Hope you find it just as useful as I did!