function deepMerge(...objects) {
return objects.reduce((acc, obj) => {
Object.entries(obj ?? {}).forEach(([key, val]) => {
acc[key] =
val && typeof val === 'object' && !Array.isArray(val)
? deepMerge(acc[key] ?? {}, val)
: val;
});
return acc;
}, {});
}
// Usage
const defaults = { theme: 'dark', font: { size: 14, family: 'mono' } };
const user = { font: { size: 16 } };
console.log(deepMerge(defaults, user));
// { theme: 'dark', font: { size: 16, family: 'mono' } }
Create a free account and build your private vault. Share publicly whenever you want.