- How to Merge Two Objects in JavaScript
- Using Object.assign()
- More Fundamentals Tutorials
- How to merge two objects in JavaScript
- You might also like.
- How to merge two objects in JavaScript
- How to merge two objects in JavaScript
- How to deep merge two objects in JavaScript
- How to merge two objects with same key in JavaScript
- How to merge two objects without overwriting in JavaScript
- Summary
- Latest Posts
- How to Print in JavaScript Console
- How to Debug in React Native
- How to Hide the Header in React Native Navigation
- How to Download a File from a URL in JavaScript
- Will Mayger
How to Merge Two Objects in JavaScript
To merge two objects in JavaScript, you can use the spread . operator. The spread operator creates a new object with all the properties from the first and second object. If there’s two properties with the same name, the property from the second object wins out.
const obj1 = < a: 1, b: 2, c: 3 >; const obj2 = < d: 4, e: 5, f: 6 >; const obj3 = ; // let user = < name: 'John Smith', age: 29 >; const changes = < name: 'John A. Smith' >; user = < . user, . changes >; //
Using Object.assign()
If you want to merge the second object into the first object, instead of creating a new object, you can use Object.assign() . The Object.assign(target, source) function merges the source into the target.
const target = a: 1, b: 2, c: 3>; const source = d: 4, e: 5, f: 6>; Object.assign(target, source); target; //
More Fundamentals Tutorials
How to merge two objects in JavaScript
There are multiple ways to merge two objects in JavaScript.
- Use the Object.assign() method or spread operator ( . ) to perform a shallow merge of two objects.
- For a deeper merge, write a custom function or use a 3rd-party library like Lodash.
The Object.assign(target, source1, soure2, . ) method was introduced in ES6. It copies all enumerable own properties of one or more source objects to a target object and returns the target object. The following example uses Object.assign() to merge the profile and job objects into the user object:
const profile = name: 'John Doe', age: 25 > const job = profession: 'IT Engineer' > const user = Object.assign(profile, job) console.log(user) //
There is no limit to the number of objects you can merge with Object.assign() . All source objects get merged into the first object. Only the target object is mutated and returned.
const obj1 = a: 1 > const obj2 = b: 2 > const obj3 = c: 3 > const obj = Object.assign(obj1, obj2, obj3) console.log(obj) //
const obj = Object.assign(>, obj1, obj2, obj3) console.log(obj) //
The properties are overwritten by other objects that have the same properties later in the order of the parameters:
const obj1 = a: 1, b: 1, c: 1 > const obj2 = b: 2, c: 2 > const obj3 = c: 3 > const obj = Object.assign(>, obj1, obj2, obj3) console.log(obj) //
ES6 introduced the spread operator ( . ) that can also be used to merge two or more objects to create a new one that has properties of the merged objects.
Note: Spread operators were first introduced in ES6 (ECMAScript 2015) but object literal spread support was added in ES9 (ECMAScript 2018).
const profile = name: 'John Doe', age: 25 > const job = profession: 'IT Engineer' > const user = . profile, . job > console.log(user) //
The object spread is a relatively new feature and only works in the latest versions of modern browsers. Similar to Object.assign() , it allows you to merge any number of objects with the identical handling of duplicate keys.
const merge = (. arguments) => // create a new object let target = > // merge the object into the target object const merger = obj => for (let prop in obj) if (obj.hasOwnProperty(prop)) target[prop] = obj[prop] > > > // iterate through all objects and merge them with target for (let i = 0; i arguments.length; i++) merger(arguments[i]) > return target > const profile = name: 'John Doe', age: 25 > const job = profession: 'IT Engineer' > const user = merge(profile, job) console.log(user) //
To deep merge two or more objects, you need to recursively copy all objects’ own properties, nested arrays, functions, and extended properties to the target object. Let us extend the above function to perform a deep merger of multiple objects:
const merge = (. arguments) => // create a new object let target = > // deep merge the object into the target object const merger = obj => for (let prop in obj) if (obj.hasOwnProperty(prop)) if (Object.prototype.toString.call(obj[prop]) === '[object Object]') // if the property is a nested object target[prop] = merge(target[prop], obj[prop]) > else // for regular property target[prop] = obj[prop] > > > > // iterate through all objects and // deep merge them with target for (let i = 0; i arguments.length; i++) merger(arguments[i]) > return target > const profile = name: 'John Doe', age: 25, address: city: 'Berlin', country: 'DE' > > const job = profession: 'IT Engineer', skills: ['JavaScript', 'React', 'Node'] > // perform deep merge const user = merge(profile, job) console.log(user) // // name: 'John Doe', // age: 25, // address: < city: 'Berlin', country: 'DE' >, // profession: 'IT Engineer', // skills: ['JavaScript', 'React', 'Node'] // >
You can also use Lodash’s merge() method to perform a deep merger of objects. This method recursively merges two or more source objects’ properties into a target object:
const _ = require('lodash') const profile = name: 'John Doe', age: 25, address: city: 'Berlin', country: 'DE' > > const job = profession: 'IT Engineer', skills: ['JavaScript', 'React', 'Node'] > // deep merge objects const user = _.merge(profile, job) console.log(user) // // name: 'John Doe', // age: 25, // address: < city: 'Berlin', country: 'DE' >, // profession: 'IT Engineer', // skills: ['JavaScript', 'React', 'Node'] // >
To learn more about JavaScript objects, prototypes, and classes, read this guide. ✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.
You might also like.
How to merge two objects in JavaScript
In this post we will cover everything about how to merge two objects in JavaScript including, deep, and shallow merges, as well as same keys and preventing overwriting keys.
Will Mayger
It is highly common to need to merge two objects in JavaScript, it is something that you may find yourself needing to do on a daily basis in pretty much any JavaScript position.
This post is going to go over everything you need to know to be able to merge two objects in JavaScript for both shallow and deep objects, objects with the same key, preventing data loss from overwriting and more.
How to merge two objects in JavaScript
The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( . ).
All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent object.
Here is an example of how you can use the spread syntax to merge two objects in JavaScript:
const objOne = a: "a" > const objTwo = . objOne, b: "b" > console.log(objTwo) //
As you can see in the above example we have pulled the properties from the first object into the second by merging the two objects with the use of the spread syntax.
It is worth noting that this will only merge to a shallow level and that if both objects share a property the second in order will overwrite the first.
What that means is it will still transfer all properties, but if you have a nested object then that object will remain nested and the properties will not be merged into the parent object.
Here is an example of this will look:
const objOne = a: "a", x: y: "y" > > const objTwo = . objOne, b: "b" > console.log(objTwo) // < a: "a", b: "b", x: < y: "y" >>
As you can see the nested object is still nested, so how can we merge it as well?
How to deep merge two objects in JavaScript
To deep merge two objects in JavaScript is a little harder to do than shallow merging which is why it is always important to normalize and try to keep your data as flat as possible to avoid needing to deep merge.
With that said, sometimes you can’t avoid having to deep merge two objects, so let’s take a look at how you can.
The first way is actually pretty simple, for most cases you will know the structure of your data, and because of that we can deep merge it manually to avoid any recursive functions having to do it for us.
To deep merge manually it is actually pretty similar to the shallow merge except we need to make sure we merge any nested objects as well using the spread syntax.
Here is an example of how a manual deep merge could look:
const objOne = a: "a", x: y: "y" > > const objTwo = . objOne, b: "b", . objOne.x > delete objTwo.x console.log(objTwo) //
If you want to avoid removing the nested object after it has been merged then you can instead selectively choose the data you want like so:
const objOne = a: "a", x: y: "y" > > const objTwo = a: objOne.a, b: "b", . objOne.x > console.log(objTwo) //
If you do not know the data within the object or you need a more generic approach, your best bet is to use a helper method like merge from lodash which will perform a deep merge for you.
However, if you don’t want to import a library just for deep merging or if you don’t want to use lodash then you will need to create a recursive function to be able to deep merge two objects.
Here is an example of a generic helper method that uses recursion to deep merge and flatten two objects in JavaScript:
function deepMergeFlatten(obj1, obj2) const keys = Object.keys(obj2) let nextObj = . obj1 > for (let i = 0; i keys.length; i += 1) const key = keys[i] const value = obj2[key] if (typeof value === "object" && value !== null) nextObj = . nextObj, . deepMergeFlatten(nextObj, value) > > else nextObj = . nextObj, [key]: value > > > return nextObj > deepMergeFlatten( a: "a" >, b: "b", c: c: "c", d: d: "d", e: e: "e" > > > > ) //
In the example above the helper method will loop over each key in an object whilst checking if the value for the key is an object or not, if the value is an object then it will call itself with the object to start the process over again with the smaller nested object, otherwise if it is not an object then it will add it into the new object.
With this recursive function, after all the objects have been found and merged together it will return a single object with all values merged together.
How to merge two objects with same key in JavaScript
When you merge two objects with the same key in JavaScript you need to decide which one will take precedence in the merged array. The one you want to key with the same key must be last in the merging of the two objects with the same key.
Here is an example of how to merge two objects with the same key in JavaScript:
const objA = a: 10 > const objB = a: 15 > console.log( . objA, . objB >) // console.log( . objB, . objA >) //
As you can see from this example you just need to make sure that you merge the two objects in the correct order to preserve the value of the key you need.
Whichever property comes last will overwrite any property with the same key before it.
How to merge two objects without overwriting in JavaScript
To merge two objects without overwriting in JavaScript is a little similar to the manual deep merge.
If you have a nested object but you don’t want to overwrite the property you just need to spread the two properties into a new version of the property.
Here is an example how you can do this:
const obj1 = a: num: 123 >, x: "x" > const obj2 = a: letters: "abc" >, z: "z" > console.log( . obj1, . obj2, a: . obj1.a, . obj2.a, >, >) // < a: < num: 123, letters: "abc" >, x: "x", z: "z" >
As you can see from this example we create a new property with precedence after merging the original two objects in, and then we use the spread syntax once again within the new version of the property for both objects with that property to extract all the keys without overwriting and losing the information.
Summary
There we have how to merge two objects in JavaScript, if you want more like this be sure to check out some of my other posts!
More money in your pocket by the end of the month.
Free to use and no account needed.
Some graphics used on this post were made using icons from flaticon.
Latest Posts
How to Print in JavaScript Console
In this post find out about how to Print in JavaScript Console
Will Mayger
How to Debug in React Native
In this post find out about how to Debug in React Native
Will Mayger
How to Hide the Header in React Native Navigation
In this post find out about how to Hide the Header in React Native Navigation
Will Mayger
How to Download a File from a URL in JavaScript
In this post find out about how to Download a File from a URL in JavaScript
Will Mayger
Will Mayger
I am a staff software engineer specializing in React, JavaScript and TypeScript with over 8 years of professional experience. I have worked with companies such as Atos, The Telegraph, Capgemini, Babylon Health and more. I am also an open source contributor to projects such as GatsbyJS.
More money in your pocket by the end of the month.
Free to use and no account needed.