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?
JSONObject to merge two JSON objects in Java. We can merge two JSON objects using the putAll() method (inherited from interface java.
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' ...}]
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}];
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' }
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With