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

AWS Q Developer image

Your AI Code Assistant

Ask anything about your entire project, code and get answers and even architecture diagrams. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Start free in your IDE

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

πŸ‘₯ Ideal for solo developers, teams, and cross-company projects

Learn more