Merge JavaScript Objects with Object.assign

Share this video with your friends

Social Share Links

Send Tweet

Object.assign is a powerful JavaScript method that allows you to merge any number of JavaScript objects together.

Kristian Freeman: [0:00] Object.assign allows you to merge as many objects as you'd like together into a new single object. In this example, I have me which just has name set to Kristian and newInfo with city set to Austin, Texas. If I wanted to merge these together, I could run console.log(Object.assign) and then pass in as many objects as I'd like, for instance, me and newInfo.

[0:25] If I save this and run it in the terminal, I can see that I get name set to Kristian and city is set to Austin, Texas. Object.assign has merged these two together into a single object. Notably, Object.assign takes multiple arguments, actually, as many as you'd like.

[0:41] If I wanted to add another object, setting age to 28, and I save it and then run it in the terminal again, you can see that it's just applied age 28 to this object, so I can pass in as many arguments as I'd like here.