Learn how to log an object in Node.js

Introduction

 

In Node.js, you get an object's string representation when you log something to the console. It is going to output the object to the shell. 

 

 

What is wrong?

Now, everything works well up to two levels of nesting. But after that, Node.js gives up, and it prints [Object] as a placeholder:

For example, 

 

const obj = {
name: 'joe',
age: 35,
person1: {
  name: 'Tony',
  age: 50,
  person2: {
    name: 'Albert',
    age: 21,
    person3: {
      name: 'Peter',
      age: 23
    }
  }
 }
}
console.log(obj)

 

Output:

 

 

Here, for person3, [Object] is printed as a placeholder of its name and age.

Solution

 

  1. The best method is to use JSON.stringify, whererepresents the number of spaces for indentation. 

 

console.log(JSON.stringify(obj, nulln))

 

Output:

 

 

  1. Another method you can use is,

 

require('util').inspect.defaultOptions.depth = null
console.log(obj)

 

Output:

 

But here, the problem is that the nested objects after level 2 are now flattened. This might be a problem for complex objects.

 

Frequently Asked Questions

 

Q1: What is a console log?

 

Ans: The console.log() is a function that prints a message to log on to the debugging console.

 

Q2: How do I iterate through a JSON object?

 

Ans: You can either use Object.values() or Object. entries(). It will return an array which we can then iterate over.  

 

Q3: How do you turn an object into an array?

 

Ans: You can use one of the three methods to convert a object into an array:

Object.keys() , Object.values() , and Object.entries() .

 

Q4: What is the JSON format?

 

Ans: JSON (JavaScript Object Notation) is a standard text-based format used to represent structured data based on JavaScript object syntax.

 

Key takeaways

Today, we learned how to log an object in Node.JS. You can simply use console.log(object) up to two levels of nesting, but after that, it prints [Object] as a placeholder.

 

To avoid this problem, we saw that we could use any of these two methods:

  1. JSON.stringify()
  2. Use util.inspect()

 

We learned that the first one is a better method because, in the second method, nested objects got flattered after two levels.

 

By- Gazal Arora

 

Was this article helpful ?
0 upvotes

Comments

No comments yet

Be the first to share what you think