AniUI Academy

Deep merge two configuration objects

hardArrays & Objects+350 XPPractice

Defaults, then workspace settings, then per-user overrides. With Object.assign a user who sets one nested option erases every other option in that branch, because the shallow copy replaces the whole sub-object.

Implement deepMerge(base, patch). Return a new object containing every key from base, with the keys from patch applied on top. Where both sides hold a plain object for the same key, merge those recursively. Where they do not, the value from patch replaces the one from base outright — so an array in patch replaces an array in base rather than concatenating with it, and a primitive in patch replaces an object in base. A key whose value in patch is undefined is skipped entirely and the value from base survives. A value of null is a real value and does overwrite. Neither input is modified.

Arguments

baseObject
The underlying object. Its keys form the starting point.
patchObject
The overriding object. Its keys are layered on top of base.

Returns

Object — A new object with patch applied on top of base, merging only where both sides hold a plain object.

Examples

deepMerge({ a: { x: 1, y: 2 } }, { a: { y: 9, z: 3 } });
// { a: { x: 1, y: 9, z: 3 } } — nested objects merge, not replace
deepMerge({ tags: [1, 2, 3] }, { tags: [9] });
// { tags: [9] } — arrays replace, they do not concatenate

deepMerge({ a: 1 }, { a: null });       // { a: null }  — null overwrites
deepMerge({ a: 1 }, { a: undefined });  // { a: 1 }     — undefined is skipped

What it has to do

  • Recursively merge keys where both sides hold a plain object.
  • Let the patch value replace the base value in every other case.
  • Replace arrays outright rather than concatenating them.
  • Skip patch keys whose value is undefined, but let null overwrite.
  • Do not mutate either input object.
Asked atMetaShopify

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +350 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.