How to open object object in javascript

(This has been added to my library at GitHub)

Reinventing the wheel here! None of these solutions worked for my situation. So, I quickly doctored up wilsonpage’s answer. This one is not for printing to screen (via console, or textfield or whatever). It does work fine in those situations and works just fine as the OP requested, for alert. Many answers here do not address using alert as the OP requested. Anyhow, It is, however, formatted for data transport. This version seems to return a very similar result as toSource(). I’ve not tested against JSON.stringify, but I assume this is about the same thing. This version is more like a poly-fil so that you can use it in any environment. The result of this function is a valid Javascript object declaration.

I wouldn’t doubt if something like this was already on SO somewhere, but it was just shorter to make it than to spend a while searching past answers. And since this question was my top hit on google when I started searching about this; I figured putting it here might help others.

Anyhow, the result from this function will be a string representation of your object, even if your object has embedded objects and arrays, and even if those objects or arrays have even further embedded objects and arrays. (I heard you like to drink? So, I pimped your car with a cooler. And then, I pimped your cooler with a cooler. So, your cooler can drink, while your being cool.)

Arrays are stored with [] instead of {} and thus dont have key/value pairs, just values. Like regular arrays. Therefore, they get created like arrays do.

Also, all string (including key names) are quoted, this is not necessary unless those strings have special characters (like a space or a slash). But, I didn’t feel like detecting this just to remove some quotes that would otherwise still work fine.

This resulting string can then be used with eval or just dumping it into a var thru string manipulation. Thus, re-creating your object again, from text.

function ObjToSource(o){ if (!o) return 'null'; var k="",na=typeof(o.length)=="undefined"?1:0,str=""; for(var p in o){ if (na) k = "'"+p+ "':"; if (typeof o[p] == "string") str += k + "'" + o[p]+"',"; else if (typeof o[p] == "object") str += k + ObjToSource(o[p])+","; else str += k + o[p] + ","; } if (na) return "{"+str.slice(0,-1)+"}"; else return "["+str.slice(0,-1)+"]";}

Let me know if I messed it all up, works fine in my testing. Also, the only way I could think of to detect type array was to check for the presence of length. Because Javascript really stores arrays as objects, I cant actually check for type array (there is no such type!). If anyone else knows a better way, I would love to hear it. Because, if your object also has a property named length then this function will mistakenly treat it as an array.

EDIT: Added check for null valued objects. Thanks Brock Adams

EDIT: Below is the fixed function to be able to print infinitely recursive objects. This does not print the same as toSource from FF because toSource will print the infinite recursion one time, where as, this function will kill it immediately. This function runs slower than the one above, so I’m adding it here instead of editing the above function, as its only needed if you plan to pass objects that link back to themselves, somewhere.

const ObjToSource=(o)=> { if (!o) return null; let str="",na=0,k,p; if (typeof(o) == "object") { if (!ObjToSource.check) ObjToSource.check = new Array(); for (k=ObjToSource.check.length;na<k;na++) if (ObjToSource.check[na]==o) return '{}'; ObjToSource.check.push(o); } k="",na=typeof(o.length)=="undefined"?1:0; for(p in o){ if (na) k = "'"+p+"':"; if (typeof o[p] == "string") str += k+"'"+o[p]+"',"; else if (typeof o[p] == "object") str += k+ObjToSource(o[p])+","; else str += k+o[p]+","; } if (typeof(o) == "object") ObjToSource.check.pop(); if (na) return "{"+str.slice(0,-1)+"}"; else return "["+str.slice(0,-1)+"]";}


var test1 = new Object(); = 1; = 2;var testobject = new Object(); = 1; = null;testobject.loop = testobject;testobject.dup = test1;console.log(ObjToSource(testobject));console.log(testobject.toSource());


{'run':1,'fast':null,'loop':{},'dup':{'foo':1,'bar':2}}({run:1, fast:null, loop:{run:1, fast:null, loop:{}, dup:{foo:1, bar:2}}, dup:{foo:1, bar:2}})

NOTE: Trying to print document.body is a terrible example. For one, FF just prints an empty object string when using toSource. And when using the function above, FF crashes on SecurityError: The operation is insecure.. And Chrome will crash on Uncaught RangeError: Maximum call stack size exceeded. Clearly, document.body was not meant to be converted to string. Because its either too large, or against security policy to access certain properties. Unless, I messed something up here, do tell!

5 Ways to Log an Object to the Console in JavaScript

Like all JavaScript developers, I love to use the console to inspect variables while I’m coding. Here are 5 methods to output an object’s keys and properties to the console window.

Photo by Mike Meyers on Unsplash

If you are like me, you’ve run into the issue of trying to log a JavaScript object or array directly to the console — but what’s the best way?

There is the argument that we should just use the debugger statement and inspect variables and objects in the Dev Tools’ debugger window.

But personally, when figuring out an algorithm or trying a new code syntax, I like to prototype quickly in the console. (Sue me! 🙂)

Here are 5 ways to log JavaScript objects directly to the console window.

Photo by Nikita Kostrykin on UnsplashMethod 1 — Use console.log(object)

When developing in a browser, the console.log() method called with an object or objects as arguments will display the object or objects.

“The Console method log() outputs a message to the web console. The message may be a single string (with optional substitution values), or it may be any one or more JavaScript objects.” — MDN Docs

Check out a code snippet using console.log(object):

And here is the screenshot resulting from that code:

The result of console.log(object)

That object’s properties can be further inspected by clicking the arrow at left:

The expanded result of console.log(object)

Of course, not all JavaScript is developed in or can be debugged in browsers — so developers may be using alert() instead of console.log().

And alert(object) does not work the same way at all — it instead shows an alert that reads [object Object]:

The result of alert(object)

The next method discussed works for both console.log() and alert().

Method 2 — Use console.log(JSON.stringify(object))

A popular method discussed online for turning objects into JavaScript strings in order to inspect them is the JSON.stringify() method.

“The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.” — MDN Docs

This is super useful if you need to substitute alert() for console.log().

Some useful tips and tricks are to use ,null,2 as additional arguments for nicely formatted indenting: console.log(JSON.stringify(obj,null,2)).

And, you can use a second argument to stringify to print only properties matching those keys: console.log(JSON.stringify(obj,["key"])).

Note that the object’s .toJSON() method will be called if it is present.

Here are a few code examples using console.log(JSON.stringify(object)):

And the screenshot resulting from those code examples:

The result of console.log(JSON.stringify(object))

JSON.stringify is great but not perfect

But watch out! JSON.stringify(object) only works with JSON-compatible data, which means certain value types can be lost.

Specifically, stringify only works for some primitives: booleans, numbers, strings, and null — but not undefined, functions, NaN, or Infinity.

Also, the stringify method also won’t work for many objects. For example, Date objects will be stringified, and RegExp objects will be simply lost.

Photo by Paweł Durczok on UnsplashMethod 3 — Use console.dir(object)

While console.log() will work for objects, there is a method specifically meant for displaying objects to the console called console.dir().

“The Console method dir() displays an interactive list of the properties of the specified JavaScript object. The output is presented as a hierarchical listing with disclosure triangles that let you see the contents of child objects.

In other words, console.dir() is the way to see all the properties of a specified JavaScript object in console by which the developer can easily get the properties of the object.” — MDN Docs

Check out this code example using console.dir(object):

And here is the resulting screenshot:

The result of console.dir(object)

Honestly, I have trouble telling the difference between console.dir(obj) and console.log(obj), at least in Firefox’s console, but both methods do exist.

Next, I cover a human-readable method meant to display tabular data.

Photo by Shane Avery on UnsplashMethod 4 — Use console.table(object)

The lesser-known console feature console.table() is perfect for displaying object data in the console window.

“This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.

It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table.

The first column in the table will be labeled (index). If data is an array, then its values will be the array indices. If data is an object, then its values will be the property names. Note that (in Firefox) console.table is limited to displaying 1000 rows (first row is the labeled index).” — MDN Docs

Here is a code snippet using console.table(object):

And the resulting screenshot, showing the tabular formatting:

Personally, I really like console.table() for quick object inspection! 💖 💯

Photo by Rohan Gangopadhyay on UnsplashMethod 5 — Use Object.entries(object)

The ES6 helper method Object.entries() can be called with an object as an argument, resulting in an array of key-value pairs.

“The Object.entries() method returns an array of a given object’s own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a loop. (The only important difference is that a loop enumerates properties in the prototype chain as well).

The order of the array returned by Object.entries() does not depend on how an object is defined. If there is a need for certain ordering, then the array should be sorted first, like Object.entries(obj).sort((a, b) => b[0].localeCompare(a[0]));.” — MDN Docs

The resulting key-value array can be iterated through using a for...of loop, allowing for more customization in terms of outputting to the console.

Check out this code using Object.entries(object) and console.log():

Here is a screenshot of the resulting output:

The result of Object.entries(object) and console.log()

Note that before ES6, you had to use a loop, as Object.entries() (and the related Object.keys() and Object.values()) are ES6 features:

Here is the resulting screenshot — it works the same as

The result of console.log() inside a loop

Again, you’ll want to explicitly use the var keyword — or let or const — because otherwise var will be implicitly declared in the global scope.

Another thing to note is that a loop will loop through inherited properties (see this part of the MDN Docs) unless you check the Object.prototype.hasOwnProperty() method for each property.

The methods Object.entries(), Object.keys(), Object.values() and Object.getOwnProperties() do not loop through inherited properties.

Of course, developers who need support for Internet Explorer can just use Babel as a polyfill instead of memorizing old code patterns. 😁

Photo by Elias Castillo on UnsplashConclusion

Every JavaScript programmer has probably output an object to the browser’s JavaScript console using console.log() at some point.

However, there are many other ways to achieve the same result — including console.dir() and my personal favorite, console.table().

The console.log(JSON.stringify(obj)) method can be useful for logging the object to the console as string, as long as the data in the object is JSON-safe.

For complex objects, the method Object.entries(obj) is a way of looping through an object that can be used to log the object to the console.

When developing outside of a browser, you may prefer to use alert() — in which case alert(JSON.stringify(obj)) and Object.entries using alert() will be the best choices to log the contents of the object inside the alert.

Whatever method you use, it is a useful skill to master the JavaScript console in order to speed up your development process. Happy coding! 💻🏆🙌

Photo by Nikita Kostrykin on UnsplashFurther reading

  • Flavio Copes reviews several methods of inspecting objects on his blog:
  • covers console tips and tricks in their article on the subject:
  • Zell Liew offers a variety of ways to loop through JS objects on his blog:

Photo by Korie Cull on Unsplash

Written by Jane