Logging objects in NodeJS

I’ve logged objects out to the console previously and had them show up, but today I logged on object out and got “[Object]” instead of the key value pairs I was expecting.

It turns out that NodeJS will only log up to two levels of nesting. If you want to log out on object with more than two levels of nesting, then the best bet is to stringify it.

Like so:

console.log(JSON.stringify(obj, null, 2))

That will indent the levels for you and everything. Hat tip to https://nodejs.dev/how-to-log-an-object-in-nodejs for teaching me that.

Leave a Reply