'Nested objects in response not logging to console

My server gets a response from another server with a document from a mongodb database with a body similar to

{
    messageDetails: {
        body: "hello"
    },
    customerDetails: {
        cstmrFirstName: 'Random',
        cstmrLastName: 'Name',
    },
}

But the response with the body is being logged to the console as:

{
  messageDetails: [Object],
  customerDetails: [Object],
}

How can I log the full object to the console with each object's properties?



Solution 1:[1]

You can use console.dir. To print with unlimited depth, use {depth: null} option:

console.dir(body, {depth: null});

Solution 2:[2]

const util = require('util')

console.log(util.inspect(objectName, {showHidden: false, depth: null, colors: true}))

Solution 3:[3]

Try console.log(JSON.stringify(body))
Checkout MDN doc JSON.stringify() for more details

Solution 4:[4]

To anyone using Deno (I didn't test this anywhere else):

To make console.dir disregard depth limits, pass a second argument with depth set to Infinity: console.dir(body, { depth: Infinity });

Based on @A1exandr Belan's answer, but changing null to Infinity, since it seems console.dir takes null as 0 and outputs just a simple [Array].

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 A1exandr Belan
Solution 2 Indira Karthikeyan
Solution 3 elainemakyl
Solution 4 AlexxNica