JavaScript

Deep Merge Objects

admin by @admin ADMIN
22h ago
Apr 28, 2026
Public
0 0 up · 0 down Sign in to vote
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
Raw
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.