Skip to content
jshacks.dev
Fundamentals

Drop keys while stringifying with a replacer

Drop or keep keys while stringifying with a replacer function or an array, and see that the array form applies to nested objects as well. Node.js 18.

2 min read
Summarize in AI

Removing password before you log an object is a job for the second argument of JSON.stringify, which takes either a function or an array. The two behave differently, and the output is from Node.js 24.

JavaScript
const user = { id: 1, name: 'Ada', password: 'secret', profile: { password: 'x', age: 36 } };

console.log(JSON.stringify(user, (key, value) => (key === 'password' ? undefined : value)));
console.log(JSON.stringify(user, ['id', 'name']));
console.log(JSON.stringify(user, ['id', 'profile', 'age']));
console.log(JSON.stringify({ at: new Date(0) }, (key, value) => (typeof value === 'string' ? value.toLowerCase() : value)));
Text
{"id":1,"name":"Ada","profile":{"age":36}}
{"id":1,"name":"Ada"}
{"id":1,"profile":{"age":36}}
{"at":"1970-01-01t00:00:00.000z"}

A function replacer runs for each key and value, and returning undefined drops the property, at any depth: profile.password went too. An array replacer is an allowlist of key names, and the third output line shows its catch: the list applies at every level, so age had to be named for the nested profile object, and without it profile would be {}. The last line shows a subtler point: the replacer lower-cases every string, and the date came out as 1970-01-01t00:00:00.000z, because it saw the text toJSON had already produced, not the Date itself. The rules are in the specification for JSON.stringify.

An allowlist is safer than a blocklist for logging, because a new sensitive field is hidden by default. The function replacer is called once first with an empty key for the whole value, so return the value unchanged there. Symbols and functions are dropped, whichever replacer you use.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.