JavaScriptFundamental (ES6), part 1
Deep merge objects in JavaScript
103 defaults, and a deep merge that keeps the branches
hardMerge a tenant's partial settings over the shipped defaults so that untouched branches survive. Show what the plain spread destroys, decide what an explicit undefined in the override means, keep arrays replaced rather than concatenated, and then look at what the key __proto__ does to your result.
Stuck? Three hints, smallest first
- 1. The spread
{ ...base, ...override }replaces whole values. That is the bug: a branch mentioned by the override loses every sibling key the override did not repeat. - 2. Recurse only when both sides are plain objects. An array, a
Date, aMapornullshould be taken whole. - 3. For
defaults, spreading lets an explicitundefinedwin.??=over the fallback keys is what "fill in the missing ones" actually means.
const isPlain = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
const deepMerge = (base, override) => {
const out = { ...base };
for (const [key, value] of Object.entries(override)) {
if (isPlain(value) && isPlain(out[key])) out[key] = deepMerge(out[key], value);
else if (value !== undefined) out[key] = value; // undefined means "no opinion"
}
return out;
};
const fillMissing = (target, fallbacks) => {
const out = { ...target };
for (const [key, value] of Object.entries(fallbacks)) out[key] ??= value;
return out;
};
const shipped = {
currency: 'NGN',
delivery: { fee: 1500, zones: ['Yaba', 'Ikeja'], window: { open: '09:00', close: '18:00' } },
retries: 3,
};
const tenant = {
delivery: { fee: 2000, window: { close: '20:00' } },
retries: undefined,
};
const merged = deepMerge(shipped, tenant);
const shallow = { ...shipped, ...tenant };
const withZones = deepMerge(shipped, { delivery: { zones: ['Lekki'] } });
const baseFeeStillThere = shipped.delivery.fee;
const branchIsNew = merged.delivery === shipped.delivery;
const zonesAreShared = merged.delivery.zones === shipped.delivery.zones;
const spreadDefaults = { ...{ fee: 1500, currency: 'USD' }, ...{ fee: undefined, currency: 'NGN' } };
const filledDefaults = fillMissing({ fee: undefined, currency: 'NGN' }, { fee: 1500, currency: 'USD' });
const risky = deepMerge({}, JSON.parse('{"__proto__":{"surcharge":9999}}'));
const pollution = [Object.hasOwn(risky, '__proto__'), risky.surcharge, JSON.stringify(risky), ({}).surcharge === undefined];
console.log('merged :', merged);
console.log('shallow :', shallow);
console.log('defaults:', spreadDefaults, '| filled:', filledDefaults);
console.log('proto :', pollution);
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('the override wins where it speaks, and the rest of the branch survives', merged.delivery, { fee: 2000, zones: ['Yaba', 'Ikeja'], window: { open: '09:00', close: '20:00' } });
test('the plain spread replaces the whole branch, losing zones and the opening time', shallow.delivery, { fee: 2000, window: { close: '20:00' } });
test('an explicit undefined is treated as no opinion here, and as an answer by the spread', [merged.retries, 'retries' in shallow, shallow.retries === undefined], [3, true, true]);
test('arrays are replaced whole, never concatenated', withZones.delivery.zones, ['Lekki']);
test('the base is untouched, and the merged branch is a new object', [baseFeeStillThere, branchIsNew], [1500, false]);
test('but a branch nobody edited is shared with the base, not copied', zonesAreShared, true);
test('spreading defaults lets an undefined overwrite a real value', spreadDefaults, { fee: undefined, currency: 'NGN' });
test('??= fills only what is genuinely missing', filledDefaults, { fee: 1500, currency: 'NGN' });
test('a __proto__ key lands on the prototype: not an own key, invisible to JSON, still readable', pollution, [false, 9999, '{}', true]);
The whole reason a deep merge exists is the second assertion. A partial override is a statement about the keys it mentions, and the spread reads it as a statement about the whole branch, so { delivery: { fee: 2000 } } silently deletes the delivery zones and the opening time. Config bugs of this kind are hard to see because the result is a valid object.
Three choices are being made, and each has a defensible opposite. Treating undefined as "no opinion" means a caller cannot deliberately clear a default — pick a sentinel like null for that. Replacing arrays rather than concatenating is what almost everyone wants, because a merged list of zones with duplicates in it is rarely the intent. And copying with a spread keeps the base intact at the top level while sharing every sub-object the override did not mention: the merged result and the defaults now point at the same zones array, so pushing to it changes both. If that matters, deep clone the base first.
The __proto__ assertion is the security one. Object.entries of a JSON.parse result does include a __proto__ key, and assigning it with out[key] = value runs the inherited setter, which swaps the prototype of the result instead of adding a property. The merged object then answers 9999 for a key it does not own and stringifies to {}, which is about as confusing as a bug gets. Real prototype pollution goes further and reaches Object.prototype itself. The fix is one line: skip __proto__, constructor and prototype, or build the result with Object.create(null).