Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate two JSON objects

I have two JSON objects with the same structure and I want to concat them together using Javascript. Is there an easy way to do this?

like image 468
Craig Avatar asked Jan 11 '09 20:01

Craig


People also ask

How do I combine two JSON objects?

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

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' ...}]


3 Answers

Based on your description in the comments, you'd simply do an array concat:

var jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23}]; var jsonArray2 = [{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}]; jsonArray1 = jsonArray1.concat(jsonArray2); // jsonArray1 = [{'name': "doug", 'id':5}, {'name': "dofug", 'id':23},  //{'name': "goud", 'id':1}, {'name': "doaaug", 'id':52}]; 
like image 53
jacobangel Avatar answered Oct 20 '22 22:10

jacobangel


If you'd rather copy the properties:

var json1 = { value1: '1', value2: '2' }; var json2 = { value2: '4', value3: '3' };   function jsonConcat(o1, o2) {  for (var key in o2) {   o1[key] = o2[key];  }  return o1; }  var output = {}; output = jsonConcat(output, json1); output = jsonConcat(output, json2); 

Output of above code is{ value1: '1', value2: '4', value3: '3' }

like image 38
user53964 Avatar answered Oct 21 '22 00:10

user53964


The actual way is using JS Object.assign.

Object.assign(target, ...sources)

MDN Link

There is another object spread operator which is proposed for ES7 and can be used with Babel plugins.

 Obj = {...sourceObj1, ...sourceObj2}
like image 21
Raunaq Sachdev Avatar answered Oct 20 '22 22:10

Raunaq Sachdev