How to Merge Objects in JavaScript

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

// 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
Copied to clipboard!

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

const aquatic = { dove: '🐼' };
const aerial = { dove: 'πŸ•Š' };

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

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

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

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
Copied to clipboard!
How to Merge Objects in JavaScript
If you would like to see more Webtips, follow @flowforfrank

Resources:

Remove ads
Remove ads

πŸ“š Get access to exclusive content

Want to get access to exclusive content? Support webtips with the price of a coffee to get access to tips, checklists, cheatsheets, and much more. β˜•

Get access Support us
Remove ads Read more on
Remove ads
Remove ads
πŸŽ‰ Thank you for subscribing to our newsletter. x 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.