(Jump to Code | Demo) We can combine and merge two javascript objects using triple dot (…) notation of ES6. This is a very handy feature as it allows to create a duplicate object or array. Generally, when we assign an object to another variable, we are not creating a copy else it’s the same object with just different name. So, any operation over it leads to the change in original object.

Triple dot (…) can be used to create an actual copy. This is not a reference of original array or object. This notation is also know as spread syntax.

Code to combine two javascript objects

var obj1 = {key1: 'val1', key2: 'val2'};
var obj2 = {key1: 'newVal1', key3: 'val3'};

var mergedObj = {...obj1, ...obj2};

// mergedObj = {key1: 'newVal1', key2: 'val2', key3: 'val3'}

Β Β Β Β Tweet this to help others

Let’s understand this code –

We have taken two sample objects – obj1 and obj2. You can see that key1 is same in both these objects. It means one of the values will lost after merging the objects. It works in the way that the value of last object sharing the same key will retain and previous ones gets lost. So, newVal1 will retain and val1 will lost.

var obj1 = {key1: 'val1', key2: 'val2'};
var obj2 = {key1: 'newVal1', key3: 'val3'};

You may also like –

Next, we are merging obj1 and obj2 using spread operator. This step first creates copies of both objects and then put their elements in a new defined object. This way multiple objects gets merged.

var mergedObj = {...obj1, ...obj2};

Live Demo

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles