How to merge two objects in JavaScript

How to merge two objects in JavaScript image

In this post we cover how to merge two objects in JavaScript using the ES6 spread syntax

To merge two objects in JavaScript there are a few different ways to do it and a few different depths that you can go to to do it. For example you might want a shallow merge or a deep merge.

This post will look into the most simplistic way to merge two objects together in JavaScript however by using ES6 spread syntax.

1const apples = { jazzApples: 5 };
2const tomatoes = { cherryTomatoes: 3 };
3
4const produce = { ...apples, ...tomatoes };
5
6console.log(produce);
7
8// { jazzApples: 5, cherryTomatoes: 3 };

In the above code we merge two objects into a new object by using spread syntax ("...") which takes all fields of an object and spreads it into what is being used.

In summary, to merge two objects together, you can use spread syntax (...) to achieve this in a single line of code.

Spread Syntax

Spread syntax (...) comes from ES6 and it essentially lets you pull out the values and fields of any object, or array into something else.

For example when merging two objects you can use the spread syntax to pull all of the fields from one object into another. Or when using an array you can pull all of the array items into another array.

Another use would be in the arguments of a function.

If you want to get all arguments passed into a function as an array you can use the spread syntax to put all the arguments into an array that you name.

Lastly, as a working example, let's say you need a function that can accept many arrays of numbers as parameters and you expect it to find the sum of all the numbers across all arrays passed into it.

One way in which you could do this would be to find all the arrays passed in using spread syntax to give you an array of arrays with numbers and then combine all the arrays into a single array of numbers using a loop and spread syntax, where each iteration you would re-define the single array to be equal to the current items it has as well as the numbers from the current iteration's array.

After that you can loop over the single array of numbers adding each one and then returning the overall value.

Further resources

Related topics

Save code?

How to merge two objects in JavaScript code example image

© 2024 MWXYZ