Deep-map every leaf of a nested object with fn(leaf, path)
A settings service sends nested configuration to the client, and several features need to rewrite its values based on where they sit: mask anything under secrets, convert every timeoutMs to seconds, prefix asset URLs with a CDN host. Implement mapLeaves(value, fn), a deep map that rebuilds the structure and replaces every leaf with fn(leaf, path).
mapLeaves(value, fn) // => a new structure with the same shape
fn(leaf, path) // => the new value for that leaf
Object.prototype or null). They are rebuilt, never passed to fn.null, undefined, functions, and non-plain objects such as Date, Map, or class instances. Leaves are passed to fn as is, not copied.value itself is a leaf, return fn(value, []).Object.prototype or null) and the same own enumerable string keys, in Object.keys order. Symbol keys and non-enumerable properties are ignored.path lists the keys from value down to the leaf: object keys as strings, array indexes as numbers. Every call gets its own path array, so fn may keep or change it.fn is called depth-first: children in key order, each container fully finished before the next sibling.TypeError whose message contains circular.value.const config = {
api: { baseUrl: 'https://api.acme.io', timeoutMs: 2500 },
secrets: { stripeKey: 'sk_live_123', webhooks: ['whsec_a', 'whsec_b'] },
retries: [100, 400],
launchedAt: new Date('2026-01-15'),
};
const safe = mapLeaves(config, (leaf, path) => {
if (path[0] === 'secrets') return '***';
if (path[path.length - 1] === 'timeoutMs') return leaf / 1000;
return leaf;
});
// => {
// api: { baseUrl: 'https://api.acme.io', timeoutMs: 2.5 },
// secrets: { stripeKey: '***', webhooks: ['***', '***'] },
// retries: [100, 400],
// launchedAt: (the same Date object),
// }
mapLeaves(config, (leaf, path) => path.join('.'));
// => { api: { baseUrl: 'api.baseUrl', ... }, secrets: { webhooks: ['secrets.webhooks.0', ...] }, ... }
mapLeaves(42, (leaf, path) => [leaf, path]); // => [42, []]
const loop = { name: 'loop' };
loop.self = loop;
mapLeaves(loop, (x) => x); // throws TypeError('... circular ...')