To display a JavaScript object in a readable format, use one of these methods depending on your needs:
1. JSON.stringify()
(Best for Serialization)
Converts an object to a formatted JSON string.
Syntax:
JSON.stringify(obj, replacer, space);
Examples:
const user = { name: "Alice", age: 30, hobbies: ["coding", "music"] };
// Basic usage
console.log(JSON.stringify(user));
// Output: {"name":"Alice","age":30,"hobbies":["coding","music"]}
// Formatted with indentation
console.log(JSON.stringify(user, null, 2));
/* Output:
{
"name": "Alice",
"age": 30,
"hobbies": [
"coding",
"music"
]
}
*/
// Filter properties with a replacer function
const filtered = JSON.stringify(user, (key, value) => key === 'age' ? undefined : value, 2);
console.log(filtered);
/* Output:
{
"name": "Alice",
"hobbies": [
"coding",
"music"
]
}
*/
Caveats:
- Fails for objects with circular references (e.g.,
obj.self = obj
). - Omits functions and
undefined
properties.
2. console.dir()
(Interactive Browser Console)
Displays an interactive list of the object’s properties.
console.dir(obj);
Example Output (Chrome DevTools):
3. console.table()
(Tabular Format for Arrays of Objects)
Renders arrays of objects as tables.
const users = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" }
];
console.table(users);
Example Output:
4. Iterate with for...in
Loop
Manually print key-value pairs:
const book = { title: "1984", author: "George Orwell", year: 1949 };
for (const key in book) {
if (book.hasOwnProperty(key)) {
console.log(`${key}: ${book[key]}`);
}
}
/* Output:
title: 1984
author: George Orwell
year: 1949
*/
5. Object.entries()
+ forEach()
(Modern Approach)
Convert the object to an array of [key, value]
pairs:
Object.entries(user).forEach(([key, value]) => {
console.log(`${key}: ${JSON.stringify(value)}`);
});
6. Display in the DOM
Render the object as text on a webpage:
<pre id="output"></pre>
const output = document.getElementById('output');
output.textContent = JSON.stringify(user, null, 2);
7. Handle Circular References
Use a custom replacer for objects with circular references:
const obj = { a: 1 };
obj.self = obj; // Circular reference
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]';
seen.add(value);
}
return value;
};
};
console.log(JSON.stringify(obj, getCircularReplacer(), 2));
/* Output:
{
"a": 1,
"self": "[Circular]"
}
*/
Comparison Table
Method | Best For | Limitations |
---|---|---|
JSON.stringify() | Debugging, API responses | Omits functions, circular references |
console.dir | Interactive exploration | Browser-only |
console.table | Arrays of objects | Limited customization |
Object.entries() | Programmatic iteration | Requires manual formatting |
DOM Display | Showing data to users | Needs HTML element |
Best Practice
- Use
JSON.stringify(obj, null, 2)
for quick debugging. - Use
console.dir
orconsole.table
for interactive inspection. - For circular references, implement a custom replacer.