How to merge objects
Short answer
The spread operator ... copies the properties of several objects into a new one:
const name = { name: 'Anna' };
const contact = { email: 'anna@example.com' };
console.log({ ...name, ...contact });Output:
{
"name": "Anna",
"email": "anna@example.com"
}Defaults and settings
If a key repeats, the value from the object on the right wins. That is handy for default settings:
const defaults = { theme: 'light', fontSize: 14, sound: true };
const userSettings = { theme: 'dark' };
const settings = { ...defaults, ...userSettings };
console.log(JSON.stringify(settings));Output:
{"theme":"dark","fontSize":14,"sound":true}Object.assign
Object.assign() copies properties into the first argument and changes it:
const target = { a: 1 };
Object.assign(target, { b: 2 }, { c: 3 });
console.log(JSON.stringify(target));Output:
{"a":1,"b":2,"c":3}Nested objects
The spread operator does not merge nested objects, it replaces them. Merge the nested level separately:
const defaults = { colors: { text: 'black', background: 'white' } };
const custom = { colors: { text: 'navy' } };
const replaced = { ...defaults, ...custom };
const merged = { ...defaults, colors: { ...defaults.colors, ...custom.colors } };
console.log(JSON.stringify(replaced.colors));
console.log(JSON.stringify(merged.colors));Output:
{"text":"navy"}
{"text":"navy","background":"white"}Common mistake
If you put the defaults on the right, they overwrite the user values:
const defaults = { theme: 'light' };
const userSettings = { theme: 'dark' };
console.log({ ...userSettings, ...defaults }.theme);Output:
lightFunctions used in this recipe
- Object.assign — Copies properties from some objects into another.
- structuredClone — Creates a deep copy of an object with all nested data.