Console.log Deep Objects
With deep object structures, console.log
can leave you wondering what's down in the depths of the objects you're printing out. Here's a quick help from Node stdlib.
The Problem
console.log
is nice for printing out the value of an object. But sometimes the object is too "deep" or too nested, and regular ol console.log
gives up, only printing [Object object]
for the deeply-nested sub-objects.
See:
const thing = {
one: {
two: {
three: {
four: {
five: 'right out'
}
}
}
}
}
console.log(thing)
// prints
// { one: { two: { three: [Object] } } }
Well, what's the value of three
!
Print Nested Objects
Node.js has a built-in util.inspect
method from the stdlib. Grab that, and print the output of util.inspect
. You can set the depth as a number or as null for infinite depth.
const util = require("util");
function deepLog(stuff) {
return util.inspect(stuff, { showHidden: false, depth: null, colors: true });
}
console.log(deepLog(thing));
// prints
// {
// one: {
// two: { three: { four: { five: 'right out' } } }
// }
// }
Visibility, insight. A veritable oracle.