JavaScript Snippet

Deep Merge Two Objects

Difficulty: Medium

Layering a defaults object under a user override is a daily need for config files, theme tokens, and React props, but `Object.assign` and spread only do shallow merges. This snippet walks from a recursive deep merge that follows nested plain objects, to an array-strategy variant that lets the caller pick concat vs replace, to a variadic version that folds an arbitrary number of layers from defaults to overrides.

Code Snippets
/

Deep Merge Two Objects

Deep Merge Two Objects

Layering a defaults object under a user override is a daily need for config files, theme tokens, and React props, but `Object.assign` and spread only do shallow merges. This snippet walks from a recursive deep merge that follows nested plain objects, to an array-strategy variant that lets the caller pick concat vs replace, to a variadic version that folds an arbitrary number of layers from defaults to overrides.

JavaScript
Medium
3 snippets
utility
code-template
recursion

489 views

7

Deep merge recurses only into plain objects so it never accidentally walks into a Date, a Map, or a class instance, all of which a naive merger would corrupt. The isPlainObject guard checks the constructor so Object.create(null) (a common dictionary pattern) and literal objects both qualify. Returning a fresh object via spread keeps the input immutable, which matters when the same defaults object is passed to many consumers. This is the version to default to for config and theme overrides.