How to Merge Objects in JavaScript

How to Merge Objects in JavaScript

Ferenc Almasi β€’ 2020 August 13 β€’ Read time 2 min read
  • twitter
  • facebook
JavaScript

From ECMAScript 2018 you can merge multiple objects together using the spread operator:

Copied to clipboard! Playground
// Merge objects with the spread operator:
const aquatic     = { dove:  'πŸ•Š'  };
const aerial      = { panda: '🐼' };
const terrestrial = { fish:  '🐟' };

const animals = { ...aquatic, ...aerial, ...terrestrial };

// Results in the following output:
{
    dove: 'πŸ•Š',
    panda: '🐼',
    fish: '🐟'
}
merge.js

But what if you try to merge two object which has the same property?

Copied to clipboard! Playground
const aquatic = { dove: '🐼' };
const aerial = { dove: 'πŸ•Š' };

const animals = { ...aquatic, ...aerial };

// Results in the following output:
{
    dove: 'πŸ•Š'
}
merge.js

The latter will rewrite the previous. If you don't have access to the spread operator in objects, you can also use Object.assign:

Copied to clipboard! Playground
const aquatic     = { dove:  'πŸ•Š'  };
const aerial      = { panda: '🐼' };
const terrestrial = { fish:  '🐟' };

// There is no limit to the amount of objects you can merge together
Object.assign(aquatic, aerial, terrestrial);

// If you want to copy everything into a brand new object,
// set the first param to an empty object:
Object.assign({}, aquatic, aerial, terrestrial);
merge.js
How to Merge Objects in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resources:

  • twitter
  • facebook
JavaScript
Did you find this page helpful?
πŸ“š More Webtips
Frontend Course Dashboard
Master the Art of Frontend
  • check Access 100+ interactive lessons
  • check Unlimited access to hundreds of tutorials
  • check Prepare for technical interviews
Become a Pro

Courses

Recommended

This site uses cookies We use cookies to understand visitors and create a better experience for you. By clicking on "Accept", you accept its use. To find out more, please see our privacy policy.