GitHub

deepMerge()

Deeply merges multiple objects/arrays into one, with options for customizing behavior.

Core Function
Objects
Arrays
Syntax
deepMerge(...sources, options)
Parameters

...sources
Object|Array

Two or more objects or arrays to merge deeply.

options
object
optional

Optional settings for the merge operation.

  • arrayConcat - Whether to concatenate arrays or overwrite (default: true)
  • clone - Whether to clone values to avoid mutation (default: true)
  • customizer - Custom merge function for specific handling
Returns

Object|Array
- A new deeply merged object or array.

Examples

Basic Object Merging

const obj1 = { a: 1, b: { c: 2 } };
const obj2 = { b: { d: 3 }, e: 4 };

const result = deepMerge(obj1, obj2);
// Result: { a: 1, b: { c: 2, d: 3 }, e: 4 }

Array Handling

const obj1 = { items: [1, 2] };
const obj2 = { items: [3, 4] };

// Default behavior (concatenate)
deepMerge(obj1, obj2);
// Result: { items: [1, 2, 3, 4] }

// Override behavior
deepMerge(obj1, obj2, { arrayConcat: false });
// Result: { items: [3, 4] }

Custom Merge Logic

const obj1 = { 
  config: { timeout: 1000, retries: 3 },
  data: [1, 2] 
};
const obj2 = { 
  config: { timeout: 2000, debug: true },
  data: [3, 4] 
};

const result = deepMerge(obj1, obj2, {
  customizer: (targetVal, sourceVal, key) => {
    // Custom logic for specific keys
    if (key === 'timeout') {
      return Math.max(targetVal, sourceVal);
    }
    // Return undefined to use default merge
    return undefined;
  }
});

// Result: {
//   config: { timeout: 2000, retries: 3, debug: true },
//   data: [1, 2, 3, 4]
// }

Multiple Objects

const base = { a: 1 };
const config = { b: 2, nested: { x: 10 } };
const overrides = { c: 3, nested: { y: 20 } };
const final = { d: 4 };

const result = deepMerge(base, config, overrides, final);
// Result: {
//   a: 1,
//   b: 2, 
//   c: 3,
//   d: 4,
//   nested: { x: 10, y: 20 }
// }

Preventing Mutation

const original = { 
  user: { name: "John", settings: { theme: "dark" } }
};

const updates = { 
  user: { settings: { notifications: true } }
};

const merged = deepMerge(original, updates);

// Original object remains unchanged
console.log(original.user.settings);
// { theme: "dark" }

console.log(merged.user.settings);
// { theme: "dark", notifications: true }