JavaScript › JSON & Data Serialization
How do you use the replacer parameter of JSON.stringify() to control what gets serialized?
IntermediateAnswer
The second argument can be an array of allowed key names, or a function called for every key/value pair that returns the value to use (or undefined to omit that key) — giving fine-grained control over the output, like excluding sensitive fields.
const user = { name: 'Sam', password: 'secret123' };
JSON.stringify(user, (key, value) => key === 'password' ? undefined : value);
// '{"name":"Sam"}'Real-world example Excluding a password or internal-only field before sending a user object to a client or logging it.