JavaScriptFundamental (ES6), part 2
Deep merge that concatenates arrays in JavaScript
103 A merge that adds to arrays instead of replacing them
fairMerge an environment override onto a default configuration: nested objects merge key by key, and arrays concatenate rather than being replaced. Show what plain spread does to the same pair, and be precise about three cases the merge has to decide — null, an explicit undefined, and two values whose types disagree.
Stuck? Three hints, smallest first
- 1. Spread copies one level. The nested object in the patch replaces the whole nested object in the base.
- 2. Recurse only when both sides are plain objects, and concatenate only when both are arrays.
- 3.
Object.entriesvisits a key whose value isundefined, so it will overwrite.
const isPlainObject = (value) =>
typeof value === 'object' &&
value !== null &&
!Array.isArray(value) &&
Object.getPrototypeOf(value) === Object.prototype;
function merge(base, patch) {
const out = { ...base };
for (const [key, value] of Object.entries(patch)) {
const current = out[key];
if (Array.isArray(current) && Array.isArray(value)) out[key] = [...current, ...value];
else if (isPlainObject(current) && isPlainObject(value)) out[key] = merge(current, value);
else out[key] = value; // including null, and including undefined
}
return out;
}
const defaults = {
baseUrl: 'https://api.adauramart.ng',
timeoutMs: 5000,
middleware: ['cors', 'logging'],
retry: { attempts: 3, baseMs: 200 },
cache: { ttlMs: 60000, keys: ['vendor', 'order'] },
region: { name: 'Lagos', code: 'LOS' },
};
const production = {
timeoutMs: 15000,
middleware: ['auth', 'rate-limit'],
retry: { attempts: 5 },
cache: { keys: ['rate'] },
region: null,
};
const spread = { ...defaults, ...production };
const merged = merge(defaults, production);
const wipedByUndefined = merge(defaults, { timeoutMs: undefined });
const typesDisagree = merge(defaults, { retry: [1, 2] });
const baseUntouched = [defaults.middleware, defaults.retry.attempts];
console.log('spread retry :', spread.retry, '<- baseMs is gone');
console.log('merged retry :', merged.retry);
console.log('middleware :', merged.middleware);
console.log('region :', merged.region, '<- null replaces, it does not merge');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('spread replaces the nested object wholesale, losing the key the patch did not mention', spread.retry, { attempts: 5 });
test('the deep merge keeps it', merged.retry, { attempts: 5, baseMs: 200 });
test('arrays concatenate rather than replace, base first', merged.middleware, ['cors', 'logging', 'auth', 'rate-limit']);
test('which happens at any depth', merged.cache, { ttlMs: 60000, keys: ['vendor', 'order', 'rate'] });
test('a scalar in the patch simply wins', [merged.timeoutMs, merged.baseUrl], [15000, 'https://api.adauramart.ng']);
test('null replaces the object instead of merging into it, because null is not a plain object', merged.region, null);
test('and an explicit undefined replaces too, so there is no way to say "leave this alone"', [wipedByUndefined.timeoutMs, 'timeoutMs' in wipedByUndefined], [undefined, true]);
test('when the two types disagree the patch wins outright', typesDisagree.retry, [1, 2]);
test('neither input was mutated on the way through', baseUntouched, [['cors', 'logging'], 3]);
The first two assertions are the reason deep merge exists. { ...defaults, ...production } copies exactly one level, so a patch that sets retry.attempts silently deletes retry.baseMs. Configuration files are the place this hurts most, because the missing key usually has a sensible default that now is not there, and the failure surfaces somewhere else entirely.
Concatenating arrays is a policy, not a law, and it needs to be a deliberate choice. It is right for middleware, plugins and allow-lists, where an environment adds to what is already there. It is wrong for a list that names a complete set — a single hosts array, say — where appending gives you the union of two environments and a request going somewhere unexpected. Whichever you pick, write it down, because a reader cannot tell from the call.
The undefined case in the seventh assertion is the sharp edge. Object.entries includes a key whose value is undefined, so { timeoutMs: undefined } overwrites a perfectly good default with nothing, and 'timeoutMs' in result is still true. If a patch may legitimately carry undefined values, skip them explicitly — and then you need a separate sentinel for "delete this key", because you have just spent the only natural way of saying it. The Object.getPrototypeOf(value) === Object.prototype line in the plain-object test is what stops the recursion walking into a Date, a Map, a class instance or a RegExp and reassembling it as a bag of properties. Those get replaced whole, which is almost always what was meant. It also excludes Object.create(null), which is a deliberate trade: it is genuinely a plain bag, and treating it as one would also let a __proto__ key in untrusted JSON reach the prototype chain, which is how prototype-pollution bugs in merge helpers get their CVEs.