DEV Community

Cover image for JS - ๐Ÿ’ก Merging multiple objects into one
Benjamin Mock
Benjamin Mock

Posted on โ€ข Originally published at codesnacks.net

6 1

JS - ๐Ÿ’ก Merging multiple objects into one

Want to get better at Web Development ๐Ÿš€๐Ÿš€๐Ÿš€? Subscribe to my weekly newsletter at https://codesnacks.net/subscribe/


Let's say you have multiple objects that you want to merge. How can we accomplish this? Without using any libraries there are two ways to do this in JavaScript:

  • Object.assign
  • ... - the object spread operator

Now let's see Object.assign in action:

const a = { x: "x", y: "y" }
const b = { z: "z" }

// create a new object and assign a & b
const c = Object.assign({}, a, b)
console.log(c) // {x: "x", y: "y", z: "z"}

The same works also with the object spread operator:

const a = { x: "x", y: "y" }
const b = { z: "z" }

// create a new object and spread a & b
const c = { ...a, ...b }
console.log(c) // {x: "x", y: "y", z: "z"}

Cool, so we can now merge multiple objects into one. You can of course also merge more than two.

But what happens when there are properties, that are named the same in both objects?

Let's see:

const a = { x: "x", y: "y", who: "I'm a" }
const b = { z: "z", who: "I'm b" }

const c = { ...a, ...b }
console.log(c) // {x: "x", y: "y", z: "z", who: "I'm b"}

So if two objects contain properties that are named the same, like the who property, the object that is used last will overwrite the properties of the former object. In our case who of a will be overwritten by who of b.

That because first, all the properties and values of a are put into the new object. Then the properties and values of b are put into the object, overwriting properties, that are already there.


Want to get better at Web Development?
๐Ÿš€๐Ÿš€๐Ÿš€subscribe to the Tutorial Tuesday โœ‰๏ธnewsletter

Image of Stellar post

Check out Episode 1: How a Hackathon Project Became a Web3 Startup ๐Ÿš€

Ever wondered what it takes to build a web3 startup from scratch? In the Stellar Dev Diaries series, we follow the journey of a team of developers building on the Stellar Network as they go from hackathon win to getting funded and launching on mainnet.

Read more

Top comments (0)

Sentry image

Make it make sense

Make sense of fixing your code with straight-forward application monitoring.

Start debugging โ†’

๐Ÿ‘‹ Kindness is contagious

Engage with a wealth of insights in this thoughtful article, cherished by the supportive DEV Community. Coders of every background are encouraged to bring their perspectives and bolster our collective wisdom.

A sincere โ€œthank youโ€ often brightens someoneโ€™s dayโ€”share yours in the comments below!

On DEV, the act of sharing knowledge eases our journey and forges stronger community ties. Found value in this? A quick thank-you to the author can make a world of difference.

Okay