JSON Merge Patch Application (RFC 7386)

Apply RFC 7386 merge patches without mutating the target, treating null as deletion, replacing arrays and rejecting unsafe object keys.

JavascriptData Integrity

Code

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

function cloneJson(value) {
  return value === undefined ? undefined : structuredClone(value);
}

export function applyMergePatch(target, patch) {
  if (!isPlainObject(patch)) return cloneJson(patch);
  const result = isPlainObject(target) ? { ...target } : {};
  for (const [key, value] of Object.entries(patch)) {
    if (key === "__proto__" || key === "constructor" || key === "prototype") {
      throw new TypeError("unsafe patch key: " + key);
    }
    if (value === null) {
      delete result[key];
      continue;
    }
    result[key] = applyMergePatch(result[key], value);
  }
  return result;
}

Inside the snippet

Count the functions isPlainObject, cloneJson and applyMergePatch as the entire surface area of JSON Merge Patch Application (RFC 7386).

A single loop drives the file — for (const [key, value] of Object.entries(patch)). Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.

Watch out for

  • The guard key === "__proto__" || key === "constructor" || key === "prototype" short-circuits the flow with an early throw when its condition holds.

Putting it to use

The primary signature is export function applyMergePatch(target, patch)

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

Core lines

return value === undefined ? undefined : structuredClone(value);
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
return prototype === Object.prototype || prototype === null;

Interactive Tools for This Topic

FAQ

Does the code validate its input?
`TypeError` is raised at the guard (`key === "__proto__" || key === "constructor" || key === "…`), so invalid state never reaches the main logic.
Are there any imports to resolve outside the language?
No. Every import resolves against the language's own modules. The file defines `isPlainObject`, `cloneJson`, `applyMergePatch` at load time.