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?
+1
A:
One solution is to use a list/array:
var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};
var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);
Result
jsons = [
{"name":"joe", "age":27},
{"name":"james", "age":32}
]
Soviut
2009-01-11 20:40:33
+1
A:
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 = jsonContat(output, json2);
Output = { value1: '1', value2: '4', value3: '3' };
+1
A:
okay, you can do this in one line of code. you'll need json2.js for this (you probably already have.). the two json objects here are unparsed strings.
json1 = '[{"foo":"bar"},{"bar":"foo"},{"name":"craig"}]';
json2 = '[{"foo":"baz"},{"bar":"fob"},{"name":"george"}]';
concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));
Breton
2009-01-11 21:24:20
+2
A:
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}];
jacobangel
2009-01-12 00:07:36
Your assumption about the value of jsonArray1 is incorrect. concat doesn't modify the original array, it returns a new array.
Breton
2009-01-12 04:05:03
You'd need to do jsonArray1 = jsonArray1.concat(jsonArray2);
Breton
2009-01-12 04:06:05
Whoops, you're right. Too much php lately :)
jacobangel
2009-01-14 16:42:55
This is basically what I did and it worked fine.
Craig
2009-02-12 04:03:32
A:
var baseArrayOfJsonObjects = [{},{}];
for (var i=0; i<arrayOfJsonObjectsFromAjax.length; i++) {
baseArrayOfJsonObjects.push(arrayOfJsonObjectsFromAjax[i]);
}
Luca Matteis
2009-01-12 05:05:57