Mar 6, 2024
•
#javascript
•
1 min read
Have you ever encountered the dreaded [object Object] when logging values to the console? It can be frustrating when you can't see what's actually inside your object. Let me show you a clearer way to log your data.
Instead of logging the object directly, use JSON.stringify() to convert it into a more understandable format.
const yourObject = {
name: "Alice",
age: 30,
skills: ["JavaScript", "React"]
};
console.log("User info:", yourObject);Console output:
User info: [object Object]Use JSON.stringify() to convert the object to a readable format:
console.log("User info:", JSON.stringify(yourObject));Console Output:
User info: {"name":"Alice","age":30,"skills":["JavaScript","React"]}Better! But still a bit hard to read.
You can pass null and 2 as the second and third arguments to JSON.stringify() to format the output with indentation:
console.log("User info:\n", JSON.stringify(yourObject, null, 2));Console Output:
User info:
{
"name": "Alice",
"age": 30,
"skills": [
"JavaScript",
"React"
]
}Now that's readable!
[object Object] confusionJSON.stringify(obj) for quick clarityJSON.stringify(obj, null, 2) for beautifully formatted output