Deep merge two configuration objects
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 replacedeepMerge({ 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 skippedWhat 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 letnulloverwrite. - Do not mutate either input object.
Stuck? The javascript course covers everything this challenge needs.
- 1.merges nested objects instead of replacing them
- 2.replaces arrays rather than concatenating
- 3.lets null overwrite but skips undefined
- 4.replaces an object with a primitive from the patch
- 5.does not mutate either input
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.