Explain Codes LogoExplain Codes Logo

Print content of JavaScript object?

javascript
json-stringify
console-log
object-printing
Alex KataevbyAlex Kataev·Aug 28, 2024
TLDR

Looking for a quick and dirty way to inspect a JavaScript object? Use JSON.stringify(). The syntax is smooth like a fresh jar of Nutella. Here's the scoop:

console.log(JSON.stringify(yourObject, null, 2)); // 2 spaces of indentation—luxury!

Just a heads up: this treats functions as randos that didn't get an invite to the party. For circular references, it just stands there awkwardly like someone forgot their lines. For these situations, consider a custom function or a library that caters to the eccentric.

All aboard the JSON.stringify train!

Transfiguring your output

JSON.stringify() can do more than just spit out your data. It can massage and shape it to fit your peculiar tastes. Add a function as the second parameter and take control!

console.log(JSON.stringify(yourObject, (key, value) => typeof value === 'number' ? value.toString() + ' 💰': value, 2 ));

Remember, there is no spoon... or Node.js

Use the mighty util.inspect() to traverse the intricate labyrinth of your objects. It tackles circular references and can even whisper sweet things about your functions.

const util = require('util'); console.log(util.inspect(yourObject, { showHidden: false, depth: null })); // Unleash the beast!

Don't forget to check the docs—your map for your coding voyage!

The browser is your friend, usually

Use the force of Chrome DevTools or just type console.log(yourObject) into your browser console. This lets you wander at your own pace, treating nested objects like open books.

The JSON.stringify diaries

Why toSource() is that ex you avoid

toSource() is a Firefox exclusive. It's alluring, but not everyone understands it. Stick to the standards, aka JSON.stringify().

The mad scientist path

Unhappy with JSON.stringify()? Hone your craft! Concoct a printObject() function that marches over properties with forEach or for...in:

function printObject(obj) { for (let key in obj) { // Key, key, who's got the key? if (obj.hasOwnProperty(key)) { console.log(`${key}: ${obj[key]} 👀`); } } }

Deep magic from ancient JSON libraries

Some JSON libraries offer fancy features that sparkle: flattening arrays or taming Date objects. They’re a hidden cave of wizardry!