Deep merge a config override into base defaults immutably
Build tools, feature-flag services, and design systems all ship a default config and let each environment override parts of it. The override only lists what changes, so the two objects must be merged deeply: nested sections are combined key by key instead of being replaced wholesale.
Implement mergeConfig(base, override). It returns a new object that contains base with override applied on top.
mergeConfig(base, override) // => a new plain object
For every key in either object:
undefined (or the key is not in override), keep the base value. If base does not have the key either, leave it out of the result.null, 0, '', and false, and a plain object replacing a non-object (or the reverse).override replaces the base value entirely.A plain object is an object whose prototype is Object.prototype or null (an object literal, JSON.parse output, or Object.create(null)). Arrays, Date, Map, class instances, and functions are not plain objects.
base or override.Date, Map, class instances, functions, primitives) is kept by reference.Object.keys).__proto__ in either input, at any depth. A config parsed from untrusted JSON must never change the prototype of the result (prototype pollution).constructor or toString are ordinary keys.const defaults = {
theme: { mode: 'light', palette: { primary: '#0055ff', accent: '#ff7a00' } },
features: { search: true, chat: false },
locales: ['en', 'fr'],
retries: 3,
};
const production = {
theme: { palette: { primary: '#002266' } },
features: { chat: true, search: undefined },
locales: ['en'],
retries: 0,
sentryDsn: 'https://key@sentry.example/1',
};
mergeConfig(defaults, production);
// => {
// theme: { mode: 'light', palette: { primary: '#002266', accent: '#ff7a00' } },
// features: { search: true, chat: true },
// locales: ['en'],
// retries: 0,
// sentryDsn: 'https://key@sentry.example/1',
// }
mergeConfig({ cache: { ttl: 60 } }, { cache: null });
// => { cache: null }
Both arguments are always plain objects.