How to output the full object or nested objects to the console in Nodejs?

April 9, 2021 - 1 min read

Sometimes when you log out the contents of an object into the console in Node.js, you may get something like this [Object] 🤧, which can be a pain sometimes to visualize the contents inside.

No more of that! 😎 You can print out the full contents using the console.dir() method then pass the object which contaitns nested objects as the first argument and then pass an options object with key of depth and value of null like this,

// A big nested object
const objectWithNestedObjects = {
  name: {
    name: {
      key: {
        key: "",
      },
    },
  },
};

// using console.dir() with depth of null
console.dir(objectWithNestedObjects, { depth: null });

/*
OUTPUT:

{
  name: { name: { key: { key: '' } } }
}

*/
  • Setting the depth: null will dig into objects recursively and then print out the contents.

See the above code live in repl.it.

You can also use an alternate way using the JSON.stringify() function.

That's all 😃!

Feel free to share if you found this useful 😃.