JavaScript

Deep Merge Objects

by @admin
12h ago
Apr 28, 2026
Public
Recursively merges two or more objects, combining nested properties rather than overwriting them. Unlike Object.assign or spread, this preserves deep keys from all sources. Useful for merging configuration objects, default settings with user overrides, and API response patching.
JavaScript
function deepMerge(...objects) {
  return objects.reduce((acc, obj) => {
    Object.entries(obj ?? {}).forEach(([key, val]) => {
      acc[key] =
        val && typeof val === 'object' && !Array.isArray(val)
          ? deepMerge(acc[key] ?? {}, val)
          : val;
    });
    return acc;
  }, {});
}

// Usage
const defaults = { theme: 'dark', font: { size: 14, family: 'mono' } };
const user     = { font: { size: 16 } };
console.log(deepMerge(defaults, user));
// { theme: 'dark', font: { size: 16, family: 'mono' } }
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.