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
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Compare Objects in JavaScript?
Next article icon

How to Deep Merge Two Objects in JavaScript ?

Last Updated : 26 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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 with merged values.

These are the following approaches:

Table of Content

  • Using Recursive Function
  • Using Spread Operator
  • Using Libraries like Lodash

Using Recursive Function

The recursive traveling through the items method is employed here in which properties are merged, for the deep merge for nested objects, the function calls itself.

Syntax:

function deepMerge(target, ...sources) {
// Implementation
}

Example: In the example below we will see how we can merge two objects using the Recursive Function approach.

JavaScript
function isObject(item) {     return (item && typeof item === 'object' && !Array.isArray(item)); }  function deepMerge(target, ...sources) {     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 } } 

Using Spread Operator

Objects can be shallow copied using the spread operator (...), by combining recursion with spread operators, it is possible to obtain a deep merging of objects.

Syntax:

function deepMerge(target, ...sources) {
// Implementation
}

Example: In the example below we will see how we can merge two objects using Spread Operator approach.

JavaScript
function isObject(item) {     return item !== null && typeof item === 'object' && !Array.isArray(item); }  function deepMerge(target, ...sources) {     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], sourceValue);                 } else {                     target[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 } } 

Using Libraries like Lodash

Lodash has a merge function that does deep merging of objects, it handles its edge cases and complexities very well which makes it a dependable choice for deep merging.

Syntax:

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

Example: In the example below we will see how we can merge two objects using Libraries like Lodash.

JavaScript
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 } }

Next Article
How to Compare Objects in JavaScript?
author
pankajbind
Improve
Article Tags :
  • JavaScript
  • Web Technologies

Similar Reads

  • How to Create a Nested Object in JavaScript ?
    JavaScript allows us to create objects having the properties of the other objects this process is called as nesting of objects. Nesting helps in handling complex data in a much more structured and organized manner by creating a hierarchical structure. These are the different methods to create nested
    4 min read
  • How to Compare Objects in JavaScript?
    Comparing objects is not as simple as comparing numbers or strings. Objects are compared based on their memory references, so even if two objects have the same properties and values, they are considered distinct if they are stored in different memory locations. Below are the various approaches to co
    3 min read
  • How to Deep-Freeze an Object in JavaScript?
    In JavaScript, freezing an object prevents it from being modified. This means you can no longer add, remove, or modify the properties of an object. However, by default, JavaScript's Object.freeze() only freezes the top level of an object, leaving nested objects or arrays mutable. To achieve immutabi
    4 min read
  • How to Extend an Object in JavaScript ?
    Extending an object in JavaScript means adding properties or methods to enhance its functionality. This can be done dynamically. The extends keyword is used to create a subclass from a parent class, enhancing object-oriented programming flexibility in JavaScript. Syntax:class childclass extends pare
    2 min read
  • How to Deep Merge Two Objects in TypeScript ?
    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 vario
    5 min read
  • How to Convert Object to Array in JavaScript?
    In this article, we will learn how to convert an Object to an Array in JavaScript. Given an object, the task is to convert an object to an Array in JavaScript. Objects and Arrays are two fundamental data structures. Sometimes, it's necessary to convert an object to an array for various reasons, such
    4 min read
  • How to Access Array of Objects in JavaScript ?
    Accessing an array of objects in JavaScript is a common task that involves retrieving and manipulating data stored within each object. This is essential when working with structured data, allowing developers to easily extract, update, or process information from multiple objects within an array. The
    4 min read
  • How to Merge Multiple Array of Object by ID in JavaScript?
    Merging multiple arrays of objects by a shared key, like ID, in JavaScript, is used when consolidating data from various sources, such as API responses or databases. This process involves combining objects that have the same key into a single object, allowing developers to manage and manipulate comp
    4 min read
  • How to work with Structs in JavaScript ?
    Structs are typically found in languages like C, C++, and similar, and they provide a way to organize related data items under one name. Typically JavaScript does not have built-in support for structs, but you can achieve similar functionality using objects. Objects in JavaScript are dynamic collect
    4 min read
  • How to compare Arrays of Objects in JavaScript?
    In JavaScript, comparing arrays of objects can be more complex than comparing primitive data types. We will discuss different ways to compare arrays of objects effectively, with detailed code examples and explanations. Syntax: Before going to detail the comparison techniques, let's first understand
    5 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