Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

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" } 
like image 848
Manu Avatar asked Jan 30 '14 07:01

Manu


People also ask

How do you join two objects in JavaScript?

The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( ... ). All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent object.

How do I combine two JSON objects with the same key?

Use concat() for arrays Assuming that you would like to merge two JSON arrays like below: var json1 = [{id:1, name: 'xxx' ...}] var json2 = [{id:2, name: 'xyz' ...}]

How do I combine two Jsons?

JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.


2 Answers

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.

like image 69
Mehran Hatami Avatar answered Sep 26 '22 03:09

Mehran Hatami


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]; 
like image 37
Suhas Gosavi Avatar answered Sep 22 '22 03:09

Suhas Gosavi