Deep Merge Configuration Objects
Merge nested config objects where later sources override earlier scalars but nested objects are combined recursively, a common layering need.
Code
export function deepMerge(...sources) {
const result = {};
for (const source of sources) {
if (!source || typeof source !== "object") continue;
for (const [key, value] of Object.entries(source)) {
const existing = result[key];
if (isPlainObject(existing) && isPlainObject(value)) {
result[key] = deepMerge(existing, value);
} else if (Array.isArray(value)) {
result[key] = value.slice();
} else {
result[key] = value;
}
}
}
return result;
}
function isPlainObject(value) {
return value !== null && typeof value === "object" && !Array.isArray(value);
}How the snippet works
Count the functions deepMerge and isPlainObject as the entire surface area of Deep Merge Configuration Objects.
Two loops stack here: for (const source of sources) selects, for (const [key, value] of Object.entries(source)) processes.
Points of care
- The guard
!source || typeof source !== "object"short-circuits the flow with an earlycontinuewhen its condition holds.
Applying it
The main signature reads export function deepMerge(...sources)
Treat deepMerge as the API: import it, and ignore the supporting code.
Statements that matter
return value !== null && typeof value === "object" && !Array.isArray(value);
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.Gitignore Template BuilderCompose clean .gitignore files by combining Node, Python, Go, Rust, Java, OS, IDE, and Docker presets with deduplication and custom rules.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- Do I need to install anything before running this?
- No — every API used here ships with the language runtime, so there is nothing to install. The file defines `deepMerge`, `isPlainObject` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.