/ Javascript

Merge Object values in JavaScript

Level - Intermediate. Read Time ~ <10 minutes.

Something which should be simple and it is. Latest mini-challenge was to merge the values and keys of 2 objects in JavaScript. The reason behind doing was to only update the fields which had changed in a MongoDB database. I won't go into that though, and keep this post to purely JavaScript.

The solution I came up with was to use the following NPM packages: -

  • deep-diff - This will compare objects and tell you all the differences. I'm just using it to see if there are any changes. It's very powerful and worth exploring the output it gives you.
  • object-assign-deep - This is where the real magic happens as in my example it takes in 2 objects and stitches then together replacing the original values with the new values.

I've thrown the code up on a GitHub Gist. I've given 2 examples. One is ES5 and another in ES6. If you are not fully comfortable with ES6, I suggest investing some time to grasp it. Not all features are supported in all browsers, you can check here

My example is below: -

To run my example locally. You'll need NodeJS installed. Then do the following: -

  • Create a file called objectMergeES5.js and copy the contents of the Gist above with the same name.
  • Within that folder you've created the file. In the terminal run npm init, skipping through all the options as an explanation of npm and package.json are out of scope for this example.
  • Then again in terminal run npm i deep-diff object-assign-deep.
  • Final terminal command to see the output node objectMergeES5.js.

Examine both london objects and you will see what has happened. Swap around the objects for the reverse behaviours.

Questions/comments below or on GitHub. In case the Gist becomes unreachable, ES6 example below for safe keeping: -

import { diff } from 'deep-diff';
import objectAssignDeep from 'object-assign-deep';

const anyChanges = (newObject, originalObject) => {
    return diff(newObject, originalObject).length > 0;
};

const mergeChanges = (newObject, originalObject) => {
    return !anyChanges(newObject, originalObject) ? originalObject : objectAssignDeep(originalObject, newObject);
};

const london1801 = {
    innerLondon: 879491,
    outerLondon: 131666,
    greaterLondon: 1011157,
    country: 'England',
};

const london2001 = {
    innerLondon: 2765975,
    outerLondon: 4406061,
    greaterLondon: 7172036,
    country: 'England',
};

console.dir(mergeChanges(london2001, london1801));