The Replacer Parameter
What you'll learn: How to control which properties get serialized and how they're transformed when converting objects to JSON strings.
Filtering During Serialization
You've learned that JSON.stringify() converts JavaScript objects into JSON strings. But what if you want to exclude sensitive data like passwords, or transform values during serialization? That's where the replacer parameter comes in—it's the optional second argument to JSON.stringify().
The replacer can be either an array or a function, giving you two ways to control the serialization process.
Array Replacer: Whitelist Properties
Pass an array of property names to include only those properties in the output:
const user = {
name: 'Alice',
age: 30,
password: 'secret123',
email: 'alice@example.com'
};
const safe = JSON.stringify(user, ['name', 'email']);
console.log(safe); // {"name":"Alice","email":"alice@example.com"}
The password is completely excluded—like a bouncer checking a guest list.
Function Replacer: Transform Values
Pass a function that receives each (key, value) pair and returns what should be serialized:
const data = {
price: 99.99,
discount: 0.15,
internal: 'admin-only'
};
const filtered = JSON.stringify(data, (key, value) => {
if (key === 'internal') return undefined; // exclude
if (typeof value === 'number') return Math.round(value); // transform
return value; // keep as-is
});
console.log(filtered); // {"price":100,"discount":0}
Returning undefined excludes a property. The function is called for every property, including nested ones, starting with the root object itself (where key is an empty string).
Key Takeaway: The replacer parameter lets you filter out properties with an array whitelist or transform/exclude values with a custom function during JSON.stringify().