How to Display JavaScript object with examples

During JavaScript application development, there are instances when we need to debug and display JavaScript objects in the console.

These objects contain enumerated keys and values enclosed within parentheses.

For instance, consider the following object

var obj = {
  id: 1,
  name: "John",
  salary: "5000",
  department: { id: 1, name: "sales" },
};

How to Print the JavaScript Object Using Console Log

The console object has a log function that prints the object or any JavaScript variable:

console.log("employee Object :" + obj);

This prints the object metadata as a string, which may not be very useful for debugging and understanding the object’s content values.

The output would be:

 employee Object :[object Object]

However, by adding a comma to the log function, the object can be printed in JSON format.

console.log("employee object json", obj);

output :

{
  "id": 1,
  "name": "John",
  "salary": "5000",
  "department": {
    "id": 1,
    "name": "sales"
  }
}

Alternatively, you can use console.dir to display an interactive list of the JavaScript object, enabling it to expand.

You can refer to my other posts about the the difference between console.log and console.dir.

console.dir("employee Object :" + obj);
console.dir("employee object json", obj);

How to Display JavaScript Object in JSON Format

The JSON.stringify function is used to print the JavaScript object in JSON format, displaying the stringified version of the JavaScript object.

console.dir(obj);
console.dir(typeof obj); // object

let jsonObj = JSON.stringify(obj);
console.dir(jsonObj);
console.dir(typeof jsonObj); //string

Output

{
  "id": 1,
  "name": "John",
  "salary": "5000",
  "department": {...}
}
object
{"id":1,"name":"John","salary":"5000","department":{"id":1,"name":"sales"}}
string

Display the Key and Values of an Object

The Object.keys and Object.values functions can be used to print the keys and values of the JavaScript object.

console.log(Object.keys(obj));
console.log(Object.values(obj));

Output

["id", "name", "salary", "department"]
[
  1,
  "John",
  "5000",
  {
    id: 1,
    name: "sales",
  }
]

Iterating through an object using a for...in loop is a standard approach. This loop iterates through an object and prints the key-value pairs using the console.log statement:

for (var item in obj) {
  console.log(obj[item], item);
}

Output

for (var item in obj) {
  console.log(obj[item], item);
}

Output

1 id
John name
5000 salary
{
  id: 1,
  name: "sales"
} department

Conclusion

In conclusion, JavaScript objects can be iterated through in multiple ways, allowing you to choose the most suitable method based on simplicity. All the solutions mentioned above work on the latest browsers.