How to Write a Recursive Deep Map Over Objects
Write a recursive deep map in JavaScript that transforms values or keys in nested objects and arrays, with cycle protection and tests. Node.js 24.

Array.prototype.map transforms a flat list. Real data is nested: an API response with objects inside arrays inside objects, a configuration tree, a form state. To trim every string, convert every date, rename every key from snake_case to camelCase or hide every secret, you need to walk the whole structure, and the natural tool is a recursive function. This post writes a deep map on Node.js 24 in stages: mapping values, mapping keys, passing the path to the callback, keeping non-plain objects intact and guarding against cycles. Each stage fixes a bug the previous one has, and each has printed output. For the data-shape question that comes first, see walking a tree structure recursively.
The recursion in one idea
A value is one of three things: an array, a plain object or a leaf, meaning anything else. A deep map handles each differently. For an array, map each element with the same function. For an object, rebuild it with each value mapped. For a leaf, apply the callback.
function deepMap(value, fn) {
if (Array.isArray(value)) {
return value.map((item) => deepMap(item, fn));
}
if (value !== null && typeof value === "object") {
return Object.fromEntries(
Object.entries(value).map(([key, inner]) => [key, deepMap(inner, fn)]),
);
}
return fn(value);
}
const data = {
name: " Ada ",
tags: [" a ", "b "],
profile: { city: " London ", age: 36 },
};
const trimmed = deepMap(data, (v) => (typeof v === "string" ? v.trim() : v));
console.log(trimmed);
console.log(data.name);{
name: 'Ada',
tags: [ 'a', 'b' ],
profile: { city: 'London', age: 36 }
}
Ada Every string in the tree was trimmed, numbers were left alone and the original was not modified, as the second output shows. The recursion has a base case, the leaf, and two recursive cases that each call deepMap on smaller pieces, which is why it terminates for any finite tree.
Notice what the callback does not see: it is called only for leaves, never for the arrays or objects. That is a design choice. A callback that could replace a whole subtree would be more powerful and harder to write. For a start, leaves are enough.
The first bug: objects that are not plain
The object branch treats every object the same, and that is wrong for a Date, a Map, a Set or a class instance.
const withDate = { when: new Date(0), tags: new Set(["a"]) };
console.log(deepMap(withDate, (v) => v));{ when: {}, tags: {} }A Date has no own enumerable keys, so Object.entries returns an empty list and the date became {}. The same for the Set. Data was destroyed by a function that looked harmless. The fix is to recurse only into plain objects, which are objects whose prototype is Object.prototype or null, and treat everything else as a leaf.
function isPlainObject(value) {
if (value === null || typeof value !== "object") return false;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
function deepMap(value, fn) {
if (Array.isArray(value)) {
return value.map((item) => deepMap(item, fn));
}
if (isPlainObject(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, inner]) => [key, deepMap(inner, fn)]),
);
}
return fn(value);
}
const result = deepMap(withDate, (v) => (v instanceof Date ? v.toISOString() : v));
console.log(result.when);
console.log(result.tags instanceof Set);1970-01-01T00:00:00.000Z
trueThe date reached the callback as a leaf, so the callback could convert it, and the Set passed through untouched. If you want to go inside a Map or Set, add branches for them. Make that a conscious decision, since a wrong default silently loses data.
Passing the key and the path
A callback that sees only the value cannot tell a password field from a name. Pass the key, and better, the whole path.
function deepMap(value, fn, path = []) {
if (Array.isArray(value)) {
return value.map((item, index) => deepMap(item, fn, [...path, index]));
}
if (isPlainObject(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, inner]) => [key, deepMap(inner, fn, [...path, key])]),
);
}
return fn(value, path);
}
const record = { user: "ada", password: "hunter2", history: [{ password: "old" }] };
const safe = deepMap(record, (v, path) => (path.at(-1) === "password" ? "[hidden]" : v));
console.log(safe);{
user: 'ada',
password: '[hidden]',
history: [ { password: '[hidden]' } ]
}The path is an array of keys and indexes from the root, such as ["history", 0, "password"], and path.at(-1) reads its last element. Passing the path lets the callback decide by location: redact everything under ["auth"], or convert only the field at ["profile", "createdAt"]. Building a new array on each step with [...path, key] costs a copy per level, which is fine for typical depths, and keeps each callback's path independent of the others.
Mapping keys
Renaming keys is the other common need: an API sends first_name, the application wants firstName. Add a second callback, or write a key-focused version.
const toCamel = (key) => key.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
function deepMapKeys(value, fn) {
if (Array.isArray(value)) {
return value.map((item) => deepMapKeys(item, fn));
}
if (isPlainObject(value)) {
return Object.fromEntries(
Object.entries(value).map(([key, inner]) => [fn(key), deepMapKeys(inner, fn)]),
);
}
return value;
}
const api = { first_name: "Ada", home_address: { street_name: "Main", zip_code: "1" }, past_jobs: [{ job_title: "x" }] };
console.log(deepMapKeys(api, toCamel));{
firstName: 'Ada',
homeAddress: { streetName: 'Main', zipCode: '1' },
pastJobs: [ { jobTitle: 'x' } ]
}Two collisions are possible and worth a thought. If both first_name and firstName exist, the later one overwrites the earlier, silently. Check for duplicates in a strict version. And note that the function maps the keys of plain objects only: data stored as string values, or keys of a Map, are untouched.
Cycles
A structure that refers to itself makes the recursion run forever, ending in RangeError: Maximum call stack size exceeded. JSON from an API cannot have cycles, but objects built in memory can: a parent that holds its children, each of which holds the parent.
function deepMapSafe(value, fn, seen = new WeakMap()) {
if (value !== null && typeof value === "object") {
if (seen.has(value)) return seen.get(value);
}
if (Array.isArray(value)) {
const out = [];
seen.set(value, out);
value.forEach((item) => out.push(deepMapSafe(item, fn, seen)));
return out;
}
if (isPlainObject(value)) {
const out = {};
seen.set(value, out);
for (const [key, inner] of Object.entries(value)) {
out[key] = deepMapSafe(inner, fn, seen);
}
return out;
}
return fn(value);
}
const node = { name: "root", children: [] };
node.children.push({ name: "child", parent: node });
const copy = deepMapSafe(node, (v) => v);
console.log(copy.children[0].parent === copy);
console.log(copy !== node);true
trueA WeakMap records, for each original object, its mapped copy. The copy is registered before its children are processed, so when the walk meets the original again it returns the copy, and the cycle is reproduced in the new structure. The result is a true copy, with the cycle intact, and distinct from the original. A WeakMap holds its keys weakly, so it does not keep the objects alive after the call. The same trick also preserves shared references: an object that appears twice maps to one copy that appears twice, instead of two separate ones.
Depth limits
Even without cycles, a very deep structure can overflow the stack, because each level uses a frame. A tree ten thousand levels deep is unusual in data and plausible in generated input. Either impose a maximum depth and throw a clear error, or rewrite the walk with an explicit stack. Say which you chose.
function deepMapLimited(value, fn, depth = 0, max = 100) {
if (depth > max) throw new RangeError(`structure deeper than ${max} levels`);
if (Array.isArray(value)) return value.map((v) => deepMapLimited(v, fn, depth + 1, max));
if (isPlainObject(value)) {
return Object.fromEntries(
Object.entries(value).map(([k, v]) => [k, deepMapLimited(v, fn, depth + 1, max)]),
);
}
return fn(value);
}
let deep = 1;
for (let i = 0; i < 150; i += 1) deep = { next: deep };
try {
deepMapLimited(deep, (v) => v);
} catch (error) {
console.log(error.name, error.message);
}RangeError structure deeper than 100 levelsA clear RangeError that names the limit is easier to diagnose than a stack overflow from deep inside the recursion.
Choosing between map, clone and walk
Deep map sits between two neighbors, and picking the right one avoids confusion. A deep clone copies a structure and keeps every value; a deep map copies it and changes the leaves. A walk, or traversal, visits every node for a side effect, such as collecting all the email addresses, and returns nothing. If your callback always returns its input, you wanted a clone, and structuredClone is the built-in answer. If it never returns anything useful, you wanted a walk, and a plain recursive loop without building new objects is cheaper.
Pick deep map when the output has the same shape as the input and the values differ. Typical cases are sanitizing a payload before logging it, converting date strings into Date objects after JSON.parse, normalizing text fields and renaming keys at an API boundary. In each, the shape is a contract with other code, and a function that changes only the leaves preserves it.
One more habit helps: run the function on a small sample and print both sides before applying it to real data. A deep transformation touches everything, so a mistake in the callback spreads to every field at once, and the fastest way to catch it is to look at one record.
Testing it
import test from "node:test";
import assert from "node:assert/strict";
test("maps leaves in nested objects and arrays", () => {
const input = { a: 1, b: [2, { c: 3 }] };
assert.deepEqual(deepMap(input, (n) => n * 10), { a: 10, b: [20, { c: 30 }] });
});
test("does not change the input", () => {
const input = { a: { b: 1 } };
deepMap(input, () => 0);
assert.deepEqual(input, { a: { b: 1 } });
});
test("keeps dates intact", () => {
const date = new Date(5);
assert.equal(deepMap({ date }, (v) => v).date, date);
});
test("passes the path to the callback", () => {
const paths = [];
deepMap({ a: [1] }, (v, path) => paths.push(path.join(".")));
assert.deepEqual(paths, ["a.0"]);
});ℹ tests 4
ℹ pass 4
ℹ fail 0

