Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
October 21, 2021 08:03 pm GMT

The trick to making console.log play nice with complex objects

console.log is useful in a lot of situations (although there are usually better ways to debug if that's what you're doing).

In the browser console.log works well with objects, you can drill down as much as you need. But in Node.js, when you look at the output of a nested object, you'll often see this:

$ console.log({a: {b: { c: {d: {}}}}}){ a: { b: { c: [Object] } } }

d: {} was replaced with [Object]. But why?

It's because the command line / terminal doesn't have a nice UI for drilling down, so Node attempts to print up to three levels deep. Beyond three levels it just prints [Object].

This is controlled by a variable in the node 'util' module, called depth, which defaults to 2. You can set it yourself here:

require('util').inspect.defaultOptions.depth = 0; // top level only, e.g.:// { a: [Object] }require('util').inspect.defaultOptions.depth = null; // print everything, e.g.: // {//  a: { b: { c: { d: {} } } }// }

It's not a great idea to change an underlying variable, as it might come back to bite later. So a cleaner way is to convert the JSON object to a string and log that. We can use node's built in JSON class and the stringify method:

complexObject = {a: {b: { c: {d: {}}}}}console.log(JSON.stringify(complexObject, null, 2))// {//   "a": {//     "b": {//       "c": {//         "d": {}//       }//     }//   }// }

Note that the 3rd parameter of JSON.stringify, Number 2, controls the number of spaces of indentation, and the 2nd parameter can be used to filter or adjust the objects and properties shown.

Now you can really see what's in those deep Objects.


Original Link: https://dev.to/ehlo_250/the-trick-to-making-consolelog-play-nice-with-complex-objects-gma

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To