Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • TypeScript Tutorial
  • TS Exercise
  • TS Interview Questions
  • TS Cheat Sheet
  • TS Array
  • TS String
  • TS Object
  • TS Operators
  • TS Projects
  • TS Union Types
  • TS Function
  • TS Class
  • TS Generic
Open In App
Next Article:
How to map Enum/Tuple to Object in TypeScript ?
Next article icon

How to Deep Merge Two Objects in TypeScript ?

Last Updated : 16 Jul, 2024
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.

Table of Content

  • Deep Merge Two Objects Using Recursive Function
  • Deep Merge Two Objects using Spread Operator
  • Deep Merge Two Objects using Libraries like Lodash
  • Using ES6 Maps for Tracking and Merging

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] = {};                 }                 // Check if the source object has already been visited                 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
How to map Enum/Tuple to Object in TypeScript ?
author
nikunj_sonigara
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • TypeScript
  • TypeScript-Questions

Similar Reads

  • How to Cast Object to Interface in TypeScript ?
    In TypeScript, sometimes you need to cast an object into an interface to perform some tasks. There are many ways available in TypeScript that can be used to cast an object into an interface as listed below: Table of Content Using the angle bracket syntaxUsing the as keywordUsing the spread operatorU
    3 min read
  • How to Iterate Array of Objects in TypeScript ?
    In TypeScript, we can iterate over the array of objects using various inbuilt loops and higher-order functions, We can use for...of Loop, forEach method, and map method. There are several approaches in TypeScript to iterate over the array of objects which are as follows: Table of Content Using for..
    4 min read
  • How to map Enum/Tuple to Object in TypeScript ?
    Mapping enum or tuple values to objects is a common practice in TypeScript for handling different data representations. This article explores various methods to map enumerations (enums) and tuples to objects, providing examples to illustrate each method. Table of Content Manually mapping Enum to Obj
    3 min read
  • How to Create an Object in TypeScript?
    TypeScript object is a collection of key-value pairs, where keys are strings and values can be any data type. Objects in TypeScript can store various types, including primitives, arrays, and functions, providing a structured way to organize and manipulate data. Creating Objects in TypescriptNow, let
    4 min read
  • How to Deep Merge Two Objects in JavaScript ?
    Typically, in JavaScript, combining two objects is a commonplace thing to do, but when it involves intricate nesting, deep merging turns out to be necessary, deep merge is the activity of taking the attributes or features from multiple objects (which have nested objects) and creating a new object wi
    3 min read
  • How to Define Interfaces for Nested Objects in TypeScript ?
    In TypeScript, defining interfaces for nested objects involves specifying the structure of each level within the object hierarchy. This helps ensure that the nested objects adhere to a specific shape or pattern. Here are step-by-step instructions on how to define interfaces for nested objects in Typ
    2 min read
  • How to Create Deep Readonly Type in Typescript?
    In TypeScript, the readonly access modifier is a powerful tool that ensures immutability by marking properties of a class as immutable. Once a property is markedreadonly, it cannot be reassigned. This is highly useful for maintaining consistent and safe data structures, especially in scenarios such
    3 min read
  • How to Iterate Over Object Properties in TypeScript
    In TypeScript, Objects are the fundamental data structures that use key-value pair structures to store the data efficiently. To iterate over them is a common task for manipulating or accessing the stored data. TypeScript is a superset of JavaScript and provides several ways to iterate over object pr
    3 min read
  • How to Check if an Object is Empty in TypeScript ?
    In TypeScript, it's common to encounter scenarios where you need to determine if an object is empty or not. An empty object typically means it contains no properties or all its properties are either undefined or null. Below are the methods to check if an object is empty or not in TypeScript: Table o
    3 min read
  • How to Create Objects with Dynamic Keys in TypeScript ?
    In TypeScript, objects with dynamic keys are those where the key names are not fixed and can be dynamically determined at runtime. This allows the creation of flexible data structures where properties can be added or accessed using variables, providing more versatile type definitions. These are the
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences