merge objects in javascript

How to Merge Two JS Objects

JavaScript objects are versatile data structures that allows you to store diverse data types in one place. It provides a compact way to store large number of data. JS objects can be easily transferred since their structure is similar to JSON. But sometimes you may need to merge two JS objects. It involves copying key value pairs from one object to another and resolving the right value in case the individual objects contain same keys. In this article, we will learn how to merge two JS objects.


How to Merge Two JS Objects

There are several simple ways to merge JS objects. We will look at some of them. There are many third-party JS libraries also that allow you to do this.

Using Object Spread

One of the simplest ways to merge two JS objects is to use something called object spread. Here is the syntax to merge objects obj1 and obj2.

let merged = {...obj1, ...obj2};

The key point is to add ‘…’ before each object that you want to merge. In this case, properties of obj2 will overwrite those of obj1.

You can use this syntax to merge any number of JS objects using a single command.

const allRules = {...obj1, ...obj2, ...obj3};

In the above example, properties of later objects overwrite the earlier ones with the same keys. So you need to order the objects according to the final value you want to retain in merged object. Please note, in this case, the merge result will be a new object and will not affect any of the original objects.

Using Object Assign

JavaScript provides Object that supports assign() function that allows you to merge objects. Here is a syntax to merge two objects.

Object.assign(obj1, obj2);

There is no limit to number of objects that can be merged with this method. Here is another example where we merge 4 objects.

const allRules = Object.assign({}, obj1, obj2, obj3, obj4);

Please note, in this case, the merge result will be a new object and will not affect any of the original objects.

Using For Loop

You can also use the old fashioned way of looping through one object and manually assigning the attributes of another object to it. Here is an example to merge two objects obj1 and obj2 using this approach.

for (var attrname in obj2) { obj1[attrname] = obj2[attrname]; }

Please note, in this case, the original object obj1 will change and become the result of merge. Also this approach is useful only for merging two objects. If you want to merge more than 2 objects, this method becomes complicated.

In this article, we have learnt how to merge JS objects. The first 2 methods are suitable for merging many objects quickly and using a simple code.

Also read:

How to Restrict Internet Access for Programs in Linux
How to Check if String is Valid Number in JavaScript
How to Detect Invalid Date in JavaScript
How to Convert Date to Another Timezone in JavaScript
How to Compare Arrays in JavaScript

Leave a Reply

Your email address will not be published.