Sometimes, During JavaScript application development, We want to debug and display the JavaScript object into the console.
The object contains enumerated keys and values enclosed with parenthesis.
For example, an object contains the 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 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 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 an interactive list of the javascript object. It 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 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 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"
}
]
Print an object using for loop
It is a 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 objects iterate in multiple ways, you can choose based on your simplicity. All are works on the latest browsers.