How to Display JavaScript object with examples

Sometimes, During JavaScript application development, We want to debug and display the JavaScript object in the console.

The object contains enumerated keys and values enclosed with parenthesis.

For example, an object contains the following things.

The below object contains keys and values as well as nested child objects

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

How to print the javascript object using the console log

console object has a log function that prints the object or any javascript variable

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

It prints the object metadata in the form of a string. However, This is not useful to debug and know the object content values. output :

 employee Object :[object Object]

if you add a comma(,) to the log function, It will print the object in json format

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

output :

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

You can also use console.dir to display an interactive list of the javascript object. It enables it to expand.

You can check my other posts about 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.

This will display the stringify version of a 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 provides keys and values functions to print the key and values of the javascript object.

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

Output

["id", "name", "salary", "department"](4)[
  (1,
  "John",
  "5000",
  {
    id: 1,
    name: "sales",
  })
];

It is a standard way to use for the loop of an object.

Iterate an object using a for-in loop and print the key and values 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
Johnname
5000salary
{
id:1,
name:"sales"
}
department

Conclusion

To Sum up, Javascript objects iterate in multiple ways, you can choose based on your simplicity. All the above solutions work on the latest browsers.