How to Merge Objects In JavaScript?

Merging two or more objects is a common task in JavaScript, whether you’re working with an API or managing states in front-end applications. JavaScript provides various ways to merge objects. In this blog, we will explore object merging and various methods to merge objects in JavaScript.

Table of Contents:

Understanding Object Merging In JavaScript

Object merging is the process of combining two or more objects into a new object. It can be categorized into two types:

  1. Shallow Merging
  2. Deep Merging

JavaScript provides various ways to achieve both types of merges. Let’s explore each of them one by one:

Shallow Merging

Shallow merging is useful when you have to merge flat objects (objects that don’t contain nested objects). There are two ways to perform shallow merging:

Using Spread Operator { … }

Spread Operator { … } is a built-in operator in JavaScript. It is a modern and concise way to merge objects. It creates a new object and copies all properties from the original object to the new object.

Example:

Javascript

Output:

AD 4nXd2dMTgGSdnbJiLFfn0WFMxj9e5UY3n6Kh Qw9tElcrtywXX UUdzNmMj5DcnaMHjT1mlTIxSFfAVg4 7KdY0A24jEDycPQcoQcpRTv TMfVP2T5koC2Ddklcn5ksUCjTr 0JZE5g?key=U AgxkTS2wXfWMPgCPAf4ZTE

Explanation: In this example, there are two objects. One is obj1, which contains name and year properties. The other object is obj2, which contains name and course properties. Both of these objects are merged with the spread operator {…}, and new objects with all combined properties are created.

Important Note:

  • Merging objects with the use of a spread operator creates a new object.
  • If properties are the same in both objects, then values from the last object overwrite the previous one.

Using Object.assign() Method

Object.assign() is another way to merge objects in JavaScript. It copies the properties from one or more source objects to a target object.

Example:

Javascript

Output:

AD 4nXdeuK3avh 4TSm cyK8Uq0NeDrHf17mL0vz8F5bBXWul3BBvCF9tUadk8g dfF6bgPO2 jAUpxqolHmXyhDoYFi1tEdk5UYgXkS2mqCJg3H6x7B6LwPe1O9az qXK3XFiINCPyAlg?key=U AgxkTS2wXfWMPgCPAf4ZTE

Explanation: In this example, the Object.assign() method is used to merge two objects. Here, in Object.assign({}, obj1, obj2), the first object ( {} ) is the target object rest of them ( obj1, obj2 ) are source objects.

Important Note:

  • Similar to the spread operator, if both objects have the same properties, then properties from the last object overwrite the previous object’s properties.

Deep Merging

Shallow merging cannot work if the object contains a nested object (an object inside another object). For merging these kinds of objects, you have to perform deep merging by using the Lodash library of JavaScript.

Using Lodash.merge() Method

Lodash is a modern JavaScript utility library that provides a merge() function to perform deep merging in JavaScript.

Example:

Javascript

Output:

AD 4nXc6If2hg87HDwkIB7RXDAa2weHU65bYOWrOT MiWaNJPG2LDe7xh8cPsq Nd47G WgRnOe7V SG2xbQNBHkiuDbIuiWroIf3xy6Yh4ouI7GbPhwJ5Zveu1gSJcZUOFPQeGphm4v?key=U AgxkTS2wXfWMPgCPAf4ZTE

Explanation: .merge() method recursively merges all properties completely. You have to first require lodash to use its .merge() method.

Merging Arrays Inside Objects

By default, the Lodash merge() method doesn’t concatenate arrays. But if you have an object that contains an array inside it, then for merging those objects, you have to use the mergeWith() method.

Example:

Javascript

Output:

AD 4nXdHkVHLvEaPjaAbDjQIhkGNU4vzwwXxkzt q73HsIAETnR7ZQannHlV2hFR4Ih3E03 9sv8lL82EElfXQn8kEJo5np5eAusLFXldxm9Fe 0QucJcvRbkAZ6fDE3OIU8aDAf8CXp?key=U AgxkTS2wXfWMPgCPAf4ZTE

Explanation: .merge() alone would overwrite the numbers array instead of merging it. Thus mergeWith() method is used to merge an object that contains an array inside it.

Conclusion

Merging objects in JavaScript can be done in various ways, like using the spread operator { … } or Object.assign() method for shallow merging and for deep merging Lodash library is used widely.
To learn more about JavaScript and practice interview questions, follow our JavaScript Interview Questions sheet, which is prepared by industry experts.

 

This collection focuses on Backend development strategies and SQL optimization techniques.-

Make A Div Fill The Height Of The Remaining Screen Space – Discover how to use make a div fill the height of the remaining screen space in this blog.

Maintain The Aspect Ratio Of A Div With Css – Discover how to use maintain the aspect ratio of a div with css in this blog.

How To Center Absolutely Positioned Element In Div Using Css – Discover how to use how to center absolutely positioned element in div using css in this blog.

Automatic Semicolon Insertion In Javascript – Discover how to use automatic semicolon insertion in javascript in this blog.

Css Grid To Horizontally Center Element – Discover how to use css grid to horizontally center element in this blog.

Css Margin 0 Auto To Horizontally Center Element – Discover how to use css margin 0 auto to horizontally center element in this blog.

Are Non Void Self Closing Tags Valid In Html5 – Discover how to use are non void self closing tags valid in html5 in this blog.

Css Masonry Layout – Discover how to use css masonry layout in this blog.

Html Computer Code Elements – Discover how to use html computer code elements in this blog.

How to Merge Two Objects In JavaScript – FAQs

Q1. How do you add properties of one object to another in JavaScript?

You can use Object.assign(target, source) or the spread operator {…obj1, …obj2} to add properties of one object to another object.

Q2. What is the fastest way to merge two objects in JavaScript?

For performing shallow merging, the spread operator (…) is the fastest and most readable method.

Q3. How to merge two nested objects in JavaScript?

You can use the .merge() method of the Lodash Library for merging two nested objects in JavaScript.

Q4. What is the alternative to Lodash?

You can use es-toolkit in place of the Lodash library.

Q5. What is the difference between object assign and spread?

Both perform shallow merging, but Object.assign() makes changes in the target object, while the spread operator creates a new object.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner