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.
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.
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)));{"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.