How to Display JavaScript object with examples


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

Object contains enumerated key and values enclosed with parenthesis.

For example, Object contains following things

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

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

console.log to print the javascript object

console object has log function which prints the an object or any javascript variable

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

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

 employee Object :[object Object]

if you add comma(,) to log function, It will prints 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 interactive list of the javascript object. This enables to expand

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

JSON.stringify function used to print the javascript object in json format.

This will displays the stringify version of an 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 key and values of an object

Object provides keys and values function to prints key and values of 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"
}
]

This is standard way to use for loop of an object

Iterate an object using for in loop and print the key and values using 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 object can be iterated in multiple ways, you can choose based on your simple, All are works on latest browsers.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.