Often we need to print a javascript object to console log or somewhere else for debugging purpose. These are some handy ways to dump javascript object to log:
Dump javascript object using JSON.stringify
Outcome will be in console <script type="text/javascript"> var obj = { k1:"v1", k2: "v2", k3: "v3"}; console.log("obj=" + JSON.stringify(obj)); </script>
obj={"k1":"v1","k2":"v2","k3":"v3"}
Dump DOM object using “for…in” loop
In case object has properties.
Outcome will be in console <script type="text/javascript"> var msg = ""; var obj = window.screen; for (var i in obj) { msg += i + "=" + obj[i] + "\n"; } console.log(msg); </script>
availWidth=1280 availHeight=773 width=1280 height=800 colorDepth=24 pixelDepth=24 availLeft=0 availTop=23 orientation=[object ScreenOrientation]
Dump objects using console format specifier
Here we’ll use %o (DOM object) and %O (Javascript object) in console.log
Outcome will be in console <script type="text/javascript"> var obj = { k1:"v1", k2: "v2", k3: "v3"}; console.log("obj=%O", obj); console.log("obj=%o", window.screen); </script>
Note that console.log may not work in old IE browsers. So this should only be used in development/debugging environment.