Deep Merge Plain Objects Safely

Merge nested configuration objects without mutation, cloning arrays and special values while blocking prototype-pollution keys.

JavascriptConfig Management

Code

javascriptsnippet
71 lines
const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);

function isPlainObject(value) {
  if (value === null || typeof value !== "object") return false;
  const prototype = Object.getPrototypeOf(value);
  return prototype === Object.prototype || prototype === null;
}

function cloneValue(value) {
  if (Array.isArray(value)) return value.map(cloneValue);
  if (value instanceof Date) return new Date(value.getTime());
  if (value instanceof Map) {
    return new Map([...value].map(([key, item]) => [key, cloneValue(item)]));
  }
  if (value instanceof Set) {
    return new Set([...value].map(cloneValue));
  }
  if (isPlainObject(value)) {
    const output = {};
    for (const [key, item] of Object.entries(value)) {
      if (!DANGEROUS_KEYS.has(key)) output[key] = cloneValue(item);
    }
    return output;
  }
  return value;
}

function mergeInto(target, source) {
  for (const [key, value] of Object.entries(source)) {
    if (DANGEROUS_KEYS.has(key) || value === undefined) continue;
    if (isPlainObject(value)) {
      const base = isPlainObject(target[key]) ? target[key] : {};
      target[key] = mergeInto({ ...base }, value);
    } else {
      target[key] = cloneValue(value);
    }
  }
  return target;
}

export function deepMerge(...sources) {
  const result = {};
  for (const source of sources) {
    if (source === undefined || source === null) continue;
    if (!isPlainObject(source)) {
      throw new TypeError("deepMerge only accepts plain objects");
    }
    mergeInto(result, source);
  }
  return result;
}

const defaults = {
  server: { host: "localhost", port: 3000, tls: false },
  tags: ["api"],
  limits: { rpm: 60 },
};
const overrides = {
  server: { port: 8080, tls: true },
  tags: ["prod", "api"],
  extra: null,
};
const merged = deepMerge(defaults, overrides, { server: { host: "0.0.0.0" } });
console.log(JSON.stringify(merged));
console.log(defaults.server.port, defaults.tags.join(","));

const polluted = deepMerge(
  defaults,
  JSON.parse('{"__proto__":{"polluted":true}}'),
);
console.log(polluted.polluted === undefined, {}.polluted === undefined);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

{"server":{"host":"0.0.0.0","port":8080,"tls":true},"tags":["prod","api"],"limits":{"rpm":60},"extra":null}
3000 api
true true

How the snippet works

Deep Merge Plain Objects Safely comes down to the functions isPlainObject, cloneValue, mergeInto and deepMerge.

The nesting pairs for (const [key, item] of Object.entries(value)) with for (const [key, value] of Object.entries(source)) — the inner runs once per outer step. Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

Returns a newly built value, leaving the inputs as they were.

What to watch for

  • The guard value === null || typeof value !== "object" short-circuits the flow with an early return when its condition holds.

Applying it

Entry signature: export function deepMerge(...sources)

deepMerge is what another module would consume; nothing else here is load-bearing for callers.

Statements that matter

return new Map([...value].map(([key, item]) => [key, cloneValue(item)]));
return new Set([...value].map(cloneValue));
const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype"]);

Interactive Tools for This Topic

FAQ

Does `deepMerge` modify its input?
It does not. Inputs are only read; the return value is freshly built.
Is there a failure path for bad input?
Validation comes first — `TypeError` marks the failure at `value === null || typeof value !== "object"`, before any partial work happens.
Are there third-party dependencies?
No. The dependency list is empty; the code stays inside the standard library. The file defines `isPlainObject`, `cloneValue`, `mergeInto` at load time.