How to log entire object in Node.js

Hello Programmers. Today in this article, I will explain how we can log an entire object in Node.js. Let’s consider an example.

const obj = {
    a: {
        b: {
            c: {
                d: {},
            },
        },
    },
};

 

Here we have an object named obj. It has two children, an integer with a value of 5 and another object which further has a couple of children, an integer and another object and this thing goes on till 4 levels of nesting.

If we try to console log this object in our console we will get the following output.

{ a: { b: { c: [Object] } } }

Here we can see that instead of showing the full object, c is replaced with “[Object]”. In Node.js after two-level of nesting, the object is shorthanded.

So how can we log the entire object?

Method 1: Using stringify method

To print the full object instead of the “[Object]” notation we can convert our object into a JSON string and then print that string. In this way, we are printing the whole object but actually dealing with strings.

The stringify method takes 3 arguments. The first is the value that we want to convert to string, the Second is a replacer function that helps to do the conversion in the desired way by replacing some values and the third is space. It is used to give indentation to the string for better readability. We can give a number or some string as the third argument. Here number represents a number of white spaces to include.

The code looks like this –

const obj = {
    a: {
        b: {
            c: {
                d: {},
            },
        },
    },
};
// Here we are converting our object to JSON string.
// The value 2 represents 2 white spaces will be used for indentation.
const fullObj = JSON.stringify(obj, null, 2);

//Here we are printing the string
console.log(fullObj);

Output –

{
  "a": {
    "b": {
      "c": {
        "d": {}
      }
    }
  }
}

Method 2: Using console.dir()

We can achieve the same using console.dir method. It allows us to specify the depth or level of nesting to be done in the output of the object. We can give value as “null” for infinite nesting.
The code looks like this –

const obj = {
    a: {
        b: {
            c: {
                d: {},
            },
        },
    },
};

// Here the value null, represents printing infinite nesting of the object.
console.dir(obj, { depth: "null" });

Output –

{
a: { b: { c: { d: {} } } }
}

You may also learn,

Leave a Reply

Your email address will not be published.