Deep Merge Configuration Objects

Merge nested config objects where later sources override earlier scalars but nested objects are combined recursively, a common layering need.

JavascriptConfig Management

Code

javascriptsnippet
21 lines
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 early continue when 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

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.