Open In App

How to Deep Merge Two Objects in TypeScript ?

Last Updated : 16 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Merging two objects in TypeScript is a common task, but when dealing with complex nested structures, a deep merge becomes necessary. A deep merge combines the properties of two or more objects, including nested objects, creating a new object with merged values. In this article, we will explore various approaches to deep merging objects in TypeScript, along with their syntax and examples.

Deep Merge Two Objects Using Recursive Function

This approach involves recursively traversing the objects and merging their properties. When encountering nested objects, the function calls itself to perform a deep merge.

Syntax:

function deepMerge<T>(target: T, ...sources: Partial<T>[]): T {
// Implementation
}

Example: Recursive Function Approach

In this example, we have two objects obj1 and obj2 with nested properties. We use a recursive function deepMerge to merge these objects deeply.

TypeScript
function isObject(item: any) {
    return (item && typeof item === 'object' && !Array.isArray(item));
}

function deepMerge(target: any, ...sources: any[]): any {
    if (!sources.length) return target;
    const source = sources.shift();

    if (isObject(target) && isObject(source)) {
        for (const key in source) {
            if (isObject(source[key])) {
                if (!target[key]) Object.assign(target, { [key]: {} });
                deepMerge(target[key], source[key]);
            } else {
                Object.assign(target, { [key]: source[key] });
            }
        }
    }
    return deepMerge(target, ...sources);
}

const obj1 = { a: { b: 1 } };
const obj2 = { a: { c: 2 } };

const merged = deepMerge({}, obj1, obj2);

console.log(merged);

Output:

{ a: { b: 1, c: 2 } }

Deep Merge Two Objects using Spread Operator

The spread operator (...) can be used to shallow copy the properties of objects. By combining spread operators with recursion, we can achieve deep merging of objects.

Syntax:

function deepMerge<T>(target: T, ...sources: Partial<T>[]): T {
// Implementation
}

Example: Spread Operator Approach

In this example, we demonstrate the spread operator approach to deep merge two objects obj1 and obj2.

TypeScript
function isObject(item: any): boolean {
    return item !== null && typeof item === 'object' && !Array.isArray(item);
}

function deepMerge<T extends object>(target: T, ...sources: Array<Partial<T>>): T {
    if (!sources.length) return target;
    const source = sources.shift();

    if (isObject(target) && isObject(source)) {
        for (const key in source) {
            if (Object.prototype.hasOwnProperty.call(source, key)) {
                const sourceValue = source[key];
                if (isObject(sourceValue) && isObject(target[key])) {
                    target[key] = deepMerge(target[key] as any, sourceValue as any);
                } else {
                    (target as any)[key] = sourceValue;
                }
            }
        }
    }
    return deepMerge(target, ...sources);
}

const obj1 = { a: { b: 1 } };
const obj2 = { a: { c: 2 } };

const merged = deepMerge({}, obj1, obj2);

console.log(merged);

Output

{ a: { b: 1, c: 2 } }

Deep Merge Two Objects using Libraries like Lodash

Lodash provides a merge function that performs deep merging of objects. It handles edge cases and complexities efficiently, making it a reliable choice for deep merging.

Syntax:

import _ from 'lodash';
const mergedObject = _.merge(object1, object2);

Example: Using Libraries like Lodash

Here, we showcase the usage of Lodash's merge function to deep merge two objects obj1 and obj2.

TypeScript
import _ from 'lodash';

const obj1 = { a: { b: 1 } };
const obj2 = { a: { c: 2 } };

const merged = _.merge(obj1, obj2);

console.log(merged);

Output:

{ a: { b: 1, c: 2 } }

Using ES6 Maps for Tracking and Merging

When dealing with complex nested structures and needing a reliable deep merge, using ES6 Map objects can provide an efficient way to track and merge properties by keeping references to visited objects. This approach helps avoid circular references and ensures that each unique object is only merged once.

This method involves using an ES6 Map to keep track of objects that have already been visited during the merge process. When a previously visited object is encountered again, the stored reference is used to ensure that objects are not duplicated but rather merged properly. This approach is particularly useful when objects have circular references or when the structure is deeply nested.

Example: Here’s how you can implement this method:

TypeScript
function isObject(item: any): boolean {
    return item !== null && typeof item === 'object' && !Array.isArray(item);
}

function deepMergeWithMap(target: any, source: any, visited = new Map<any, any>()) {
    if (isObject(target) && isObject(source)) {
        for (const key in source) {
            if (isObject(source[key])) {
                if (!target[key]) {
                    target[key] = {};
                }
                if (!visited.has(source[key])) {
                    visited.set(source[key], {});
                    deepMergeWithMap(target[key], source[key], visited);
                } else {
                    target[key] = visited.get(source[key]);
                }
            } else {
                target[key] = source[key];
            }
        }
    }
    return target;
}

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

const merged = deepMergeWithMap(obj1, obj2);
console.log(merged);


Output:

{
"a": { "b": 1, "c": { "d": 2 } },
"e": { "b": 1 }
}

This method provides a robust solution for deep merging by using ES6 Maps to handle complexities such as circular references and deeply nested structures efficiently.


Next Article

Similar Reads