Sub topic 6
Filtering and Transforming Output with a Replacer
This chapter assumes you already know how JSON.stringify works with one argument, and which values it drops or turns into null (undefined, functions, symbols, NaN). It also assumes you can tell an arrow function from a regular function, because the difference matters for this below.
JSON.stringify takes an optional second argument called the replacer. The replacer is either a function that sees every key/value pair before it is written, or an array that lists which property names may appear in the output. The replacer lets you remove secrets, rename or reshape values, and convert types that JSON cannot represent, all without changing the original object.
The Two Forms of Replacer
| Form | What it does | Applies to | Typical use |
|---|---|---|---|
| Function `(key, value) => newValue` | Called for every property and array element. Its return value is what gets serialized. | Objects and arrays, at every depth | Redaction, type conversion, reshaping |
| Array of strings or numbers | Allowlist of property names. Any other key is skipped. | Object keys at every depth (array indices are never filtered) | Fixed public "views" of an object |
| Anything else (`null`, `undefined`, an object) | Ignored | Nothing | Pass `null` when you only want the third `space` argument |
The basic pattern looks like this:
const account = { id: 7, user: "ada", password: "secret" };
console.log(JSON.stringify(account, (key, value) =>
key === "password" ? undefined : value
));
// {"id":7,"user":"ada"}
console.log(JSON.stringify(account, ["id", "user"]));
// {"id":7,"user":"ada"}Both lines produce the same result here. The rest of the chapter explains how each form behaves when the data is nested, typed, or shaped in unexpected ways.
How the Replacer Function Is Called
The traversal order
JSON.stringify walks the value depth-first, in the same order it writes the output. It calls the replacer once for each value it is about to serialize. Logging every call shows the order:
const data = { a: 1, b: [10, 20], c: { d: true } };
JSON.stringify(data, function (key, value) {
console.log(JSON.stringify(key), "->", value);
return value;
});
// "" -> { a: 1, b: [ 10, 20 ], c: { d: true } }
// "a" -> 1
// "b" -> [ 10, 20 ]
// "0" -> 10
// "1" -> 20
// "c" -> { d: true }
// "d" -> trueThe output shows several points that people often miss:
- The first call has an empty-string key.
JSON.stringifywraps your value in a hidden holder object{ "": value }and calls the replacer for that one property. This root call happens before anything else. - Array indices arrive as strings. The key for the first element is
"0", not0. A check likekey === 0never matches. - Parents come before children. The replacer sees the whole array
[10, 20]before it sees10and20. If you replace the parent, the children you see next are the children of your replacement.
`this` is the holder object
Inside a regular function, this is the object or array that holds the current property. value is usually the same as this[key], with one important exception covered below. Arrow functions do not get their own this, so use a regular function whenever you need the holder.
What the Return Value Means
The replacer's return value replaces the original value in the output. The usual rules for unsupported values still apply to whatever you return.
Returning `undefined` removes a property, but not an array slot
In an object, returning undefined removes the property. In an array, an element cannot be removed without shifting the indices of the elements after it, so the slot becomes null:
const out = JSON.stringify({ keep: 1, drop: 2, list: [1, 2, 3] }, (key, value) =>
value === 2 ? undefined : value
);
console.log(out);
// {"keep":1,"list":[1,null,3]}To actually remove array elements, filter the array when the replacer reaches it:
const out = JSON.stringify({ list: [1, 2, 3] }, (key, value) =>
Array.isArray(value) ? value.filter((n) => n !== 2) : value
);
console.log(out);
// {"list":[1,3]}Returning `undefined` from the root call
When the replacer returns undefined for the root call (key ""), the entire result is undefined. That is the JavaScript value undefined, not the string "undefined":
console.log(JSON.stringify({ a: 1 }, () => undefined)); // undefinedYou can hit this by accident. A replacer written with braces and no return statement returns undefined for every call:
// Bug: the arrow body has braces but no return
const broken = JSON.stringify({ a: 1 }, (key, value) => {
if (key === "secret") value = "***";
});
console.log(broken); // undefinedReturned objects are traversed too
When you return an object or array, JSON.stringify descends into it and calls the replacer on its properties. This makes type conversion composable. It also means a replacer that wraps every object in a new object will loop until the call stack overflows.
Practical Patterns
Redacting sensitive keys at any depth
A function replacer sees nested keys, so a single rule covers the whole tree:
const SENSITIVE = new Set(["password", "token", "ssn"]);
function redact(key, value) {
return SENSITIVE.has(key) ? "[REDACTED]" : value;
}
const request = {
user: { name: "ada", password: "hunter2" },
headers: { token: "abc123", accept: "application/json" }
};
console.log(JSON.stringify(request, redact));
// {"user":{"name":"ada","password":"[REDACTED]"},"headers":{"token":"[REDACTED]","accept":"application/json"}}Returning a marker such as "[REDACTED]" instead of undefined keeps the shape visible in logs, which helps debugging. Return undefined when the consumer must not even learn that the field exists.
Converting Map and Set
By default, Map and Set serialize as {}, because they have no enumerable own properties. A replacer can convert them into a tagged structure:
function typedReplacer(key, value) {
if (value instanceof Map) return { __type: "Map", entries: [...value] };
if (value instanceof Set) return { __type: "Set", values: [...value] };
return value;
}
const state = { scores: new Map([["ada", 10]]), seen: new Set([1, 2]) };
console.log(JSON.stringify(state, typedReplacer));
// {"scores":{"__type":"Map","entries":[["ada",10]]},"seen":{"__type":"Set","values":[1,2]}}The __type tag gives a reviver on the parsing side enough information to rebuild the original types. Revivers get their own chapter.
The `toJSON` ordering gotcha with Dates
toJSON runs before the replacer. A Date has a built-in toJSON, so by the time your replacer sees a date, value is already an ISO string. To reach the original object, read this[key]:
const log = { at: new Date(0), msg: "boot" };
const out = JSON.stringify(log, function (key, value) {
if (this[key] instanceof Date) {
console.log(typeof value); // "string"
return this[key].getTime(); // epoch milliseconds instead of ISO text
}
return value;
});
console.log(out);
// {"at":0,"msg":"boot"}The same check written as an arrow function fails, because this would not be the holder object. The reverse also catches people out. toJSON is not called again on a value your replacer returns, so returning new Date(0) from a replacer serializes as {}. Return a string or number instead.
The Replacer Array in Detail
Rules for the allowlist
- Strings and numbers in the array are accepted. Numbers are converted to strings, so
[1]allows the key"1".StringandNumberwrapper objects are also accepted. Every other entry is ignored. - Duplicates are removed.
- Output key order follows the array, not the object's own key order.
- The list applies at every nesting level, and array elements are always kept.
The nested-container trap
Because the same list filters every level, a nested object is dropped unless its own key is in the list:
const order = {
id: 1,
customer: { id: 9, name: "Ada", email: "[email protected]" },
items: [{ id: 3, sku: "X-1", price: 5 }]
};
console.log(JSON.stringify(order, ["id", "customer"]));
// {"id":1,"customer":{"id":9}}
console.log(JSON.stringify(order, ["items", "id", "sku", "customer", "name"]));
// {"items":[{"id":3,"sku":"X-1"}],"id":1,"customer":{"id":9,"name":"Ada"}}The first call drops items entirely, and customer keeps only id, because name is not on the list. The second call shows the output following the list order: items comes first. It also shows that a key allowed for one object is allowed for all of them. Because sku and name are listed, both survive wherever they appear.
If you need different fields at different depths, use a function replacer, or build the output shape explicitly with a small mapping function.
Choosing Between Function, Array, and Explicit Mapping
| Need | Best choice | Why |
|---|---|---|
| Same small set of keys at every level | Array | Short, declarative, no code paths to test |
| Hide keys by name anywhere in the tree | Function | One rule, any depth |
| Convert types (Map, Set, BigInt, Date format) | Function | Only a function can change values |
| Different fields per level, or an API response shape | Explicit mapping before `stringify` | Clearer and type-checkable; a replacer that tracks depth becomes hard to read |
| Hot path with large payloads | No replacer, or a pre-mapped object | The function runs once per value and adds measurable overhead |
The replacer can be combined with the third space argument, for example JSON.stringify(obj, redact, 2). If you want indentation without filtering, pass null as the replacer.
Exercise
What does this print, and why? console.log(JSON.stringify({ a: [1, 2], b: 2 }, (k, v) => (v === 2 ? undefined : v)))
Show answer
It prints {"a":[1,null]}. The replacer returns undefined for every value equal to 2. Property b is an object property, so it is omitted. The second element of a is an array slot, so it becomes null to keep the indices stable. The root object and the array itself are not equal to 2, so they pass through unchanged.
Exercise
A teammate writes JSON.stringify(event, (key, value) => value instanceof Date ? value.getTime() : value) but still gets ISO strings in the output. Explain the cause and give a fix.
Show answer
Date.prototype.toJSON runs before the replacer, so value is already an ISO string when the replacer sees it, and the instanceof check never matches. Use a regular function and inspect the holder: JSON.stringify(event, function (key, value) { return this[key] instanceof Date ? this[key].getTime() : value; }). An arrow function will not work, because it does not receive the holder as this.
Exercise
Given const u = { name: "Ada", profile: { name: "ada99", bio: "hi" } }, what does JSON.stringify(u, ["name"]) return, and what change keeps the profile's name but not its bio?
Show answer
It returns {"name":"Ada"}. The profile key is not in the allowlist, so the whole nested object is skipped. Use ["name", "profile"]. The output is then {"name":"Ada","profile":{"name":"ada99"}}, because the same list filters the nested object and bio is not on it.