[javascript] How to join two JavaScript Objects, without using JQUERY

I have two json objects obj1 and obj2, i want to merge them and crete a single json object. The resultant json should have all the values from obj2 and the values from obj1 which is not present in obj2.

Question:

var obj1 = {
    "name":"manu",
    "age":23,
    "occupation":"SE"
}

var obj2 = {
    "name":"manu",
    "age":23,
    "country":"india"
}

Expected:

var result = {
    "name":"manu",
    "age":23,
    "occupation":"SE",
    "country":"india"
}

This question is related to javascript

The answer is


1)

var merged = {};
for(key in obj1)
    merged[key] = obj1[key];
for(key in obj2)
    merged[key] = obj2[key];

2)

var merged = {};
Object.keys(obj1).forEach(k => merged[k] = obj1[k]);
Object.keys(obj2).forEach(k => merged[k] = obj2[k]);

OR

Object.keys(obj1)
    .concat(Object.keys(obj2))
    .forEach(k => merged[k] = k in obj2 ? obj2[k] : obj1[k]);

3) Simplest way:

var merged = {};
Object.assign(merged, obj1, obj2);

This simple function recursively merges JSON objects, please notice that this function merges all JSON into first param (target), if you need new object modify this code.

var mergeJSON = function (target, add) {
    function isObject(obj) {
        if (typeof obj == "object") {
            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    return true; // search for first object prop
                }
            }
        }
        return false;
    }
    for (var key in add) {
        if (add.hasOwnProperty(key)) {
            if (target[key] && isObject(target[key]) && isObject(add[key])) {
                this.mergeJSON(target[key], add[key]);
            } else {
                target[key] = add[key];
            }
        }
    }
    return target;
};

BTW instead of isObject() function may be used condition like this:

JSON.stringify(add[key])[0] == "{"

but this is not good solution, because it's will take a lot of resources if we have large JSON objects.


Just another solution using underscore.js:

_.extend({}, obj1, obj2);

There are couple of different solutions to achieve this:

1 - Native javascript for-in loop:

const result = {};
let key;

for (key in obj1) {
  if(obj1.hasOwnProperty(key)){
    result[key] = obj1[key];
  }
}

for (key in obj2) {
  if(obj2.hasOwnProperty(key)){
    result[key] = obj2[key];
  }
}

2 - Object.keys():

const result = {};

Object.keys(obj1)
  .forEach(key => result[key] = obj1[key]);

Object.keys(obj2)
  .forEach(key => result[key] = obj2[key]);

3 - Object.assign():
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)

const result = Object.assign({}, obj1, obj2);

4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):

Defined in several sections of the specification: Array Initializer, Argument Lists

Using this new syntax you could join/merge different objects into one object like this:

const result = {
  ...obj1,
  ...obj2,
};

5 - jQuery.extend(target, obj1, obj2):

Merge the contents of two or more objects together into the first object.

const target = {};

$.extend(target, obj1, obj2);

6 - jQuery.extend(true, target, obj1, obj2):

Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.

const target = {};

$.extend(true, target, obj1, obj2);

7 - Lodash _.assignIn(object, [sources]): also named as _.extend:

const result = {};

_.assignIn(result, obj1, obj2);

8 - Lodash _.merge(object, [sources]):

const result = _.merge(obj1, obj2);

There are a couple of important differences between lodash's merge function and Object.assign:

1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:

_.isEqual(_.merge({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
}), {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // true

BUT:

const result = Object.assign({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
});
_.isEqual(result, {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // false
// AND
_.isEqual(result, {
  x: {
    y: {
      key2: 'value2',
    },
  },
}); // true

2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:

_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false

BUT:

_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true

Update 1:

When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype. To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.


Update 2:

I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.


Update 3:
I added the difference between Object.assign and _.merge.


I've used this function to merge objects in the past, I use it to add or update existing properties on obj1 with values from obj2:

var _mergeRecursive = function(obj1, obj2) {

      //iterate over all the properties in the object which is being consumed
      for (var p in obj2) {
          // Property in destination object set; update its value.
          if ( obj2.hasOwnProperty(p) && typeof obj1[p] !== "undefined" ) {
            _mergeRecursive(obj1[p], obj2[p]);

          } else {
            //We don't have that level in the heirarchy so add it
            obj1[p] = obj2[p];

          }
     }
}

It will handle multiple levels of hierarchy as well as single level objects. I used it as part of a utility library for manipulating JSON objects. You can find it here.


WORKING FIDDLE

Simplest Way with Jquery -

var finalObj = $.extend(obj1, obj2);

Without Jquery -

var finalobj={};
for(var _obj in obj1) finalobj[_obj ]=obj1[_obj];
for(var _obj in obj2) finalobj[_obj ]=obj2[_obj];