Explain Codes LogoExplain Codes Logo

How can I merge properties of two JavaScript objects dynamically?

javascript
object-merging
javascript-objects
polyfill
Nikita BarsukovbyNikita Barsukov·Aug 31, 2024
TLDR

To merge two objects in JavaScript: use the spread operator (...). It combines and overwrites duplicate keys in a snap.

const obj1 = { a: 1, b: 2 }; const obj2 = { b: 3, c: 4 }; const merged = { ...obj1, ...obj2 }; // result: { a: 1, b: 3, c: 4 }

In the case of conflicting keys, the latter object prevails.

Multi objects & Legacy Browsers

To make your code work across multiple objects or in older browsers, follow these steps:

Merging Multiple Objects

With more than two objects, go for Object.assign:

const merged = Object.assign({}, obj1, obj2, obj3 /*, ... , objN*/);

This method gives you a shiny new object containing an amalgamation of all objects passed with possible duplicates overridden by the last object's properties.

Promoting Browser Compatibility

Object.assign might give you the cold shoulder in certain old environments. Here, a polyfill or Babel transpilation can come to your rescue:

  • Polyfill: Add a hand-crafted function imitating Object.assign.
  • Babel: Use @babel/plugin-proposal-object-rest-spread to make spread syntax work even with that oldie browser of yours.

The ES5 Way

Using ES5? No worries. Here's a custom function for that:

function mergeObjects(obj1, obj2) { var merged = {}; // A plumber to fix the leaks between the two objects for (var prop in obj1) { if (obj1.hasOwnProperty(prop)) { merged[prop] = obj1[prop]; // Obj1: "Tag, you're it!" } } for (var prop in obj2) { if (obj2.hasOwnProperty(prop)) { merged[prop] = obj2[prop]; // Obj2: "No, tag, YOU'RE it!" } } return merged; }

Advanced techniques

Take a dive into the advanced realm of deep merges and special cases.

Diving Deep with mergeRecursive

Nested objects? Bring it on! Craft a function, mergeRecursive, that goes deeper than a submarine:

function mergeRecursive(target, source) { for (var key in source) { if (source[key] && typeof source[key] === 'object') { target[key] = mergeRecursive(target[key] || {}, source[key]); // Going deeper... } else { target[key] = source[key]; // Copying values } } return target; }

Handling Immutable Objects

Dealing with immutable objects? Use libraries like Immutable.js to preserve the initial state while copying:

import { Map } from 'immutable'; const obj1Map = Map(obj1); const obj2Map = Map(obj2); const mergedMap = obj1Map.merge(obj2Map); // Combining like a charm! const mergedObj = mergedMap.toObject();

Conflict Resolution

Before merging, have a quick match-up between property compatibility to prevent conflicts:

function canMerge(obj1, obj2) { // Insert conflict-resolving checks here // Return true if they make a friendly pair, false if otherwise }

Reiterating for emphasis – whenever possible, stick with native JavaScript functions for a buoyant performance and shiny control over third-party libraries.