Apps often build their settings in layers: a set of defaults, then what the team saved, then what the user picked. A plain spread ({ ...defaults, ...user }) only works one level deep. If the user sets just theme.font.size, the spread throws away every other key inside theme. Write deepMerge(target, source) that combines two objects at every level of nesting.
const defaults = {
theme: { color: "blue", font: { size: 14, family: "sans" } },
plugins: ["spellcheck"],
};
const user = {
theme: { font: { size: 16 } },
plugins: ["wordcount"],
};
deepMerge(defaults, user);
// {
// theme: { color: "blue", font: { size: 16, family: "sans" } },
// plugins: ["spellcheck", "wordcount"],
// }
Rules
- Return a new object. Do not change
target or source, and do not share nested plain objects or arrays with them: editing the result must never change an input.
- When both sides hold a plain object (made with
{} or Object.create(null)) for a key, merge them with the same rules.
- When both sides hold an array, join them: the target's items first, then the source's.
- In every other case the source value wins. This includes
null, and keys where the two types do not match (an object over an array, a number over an object, and so on).
- If the source value is
undefined, keep the target value.
- Values that are objects but not plain, such as
Date, Map or class instances, are copied over as they are, not merged or cloned.
- Skip any
__proto__ key in the inputs, so that a merge of untrusted JSON can't change Object.prototype.