I have two json objects:
http://example.com/search.json?section=saloon
and
http://example.com/search.json?section=coupe
I have been looking for a way to combine these two objects into one object.
Thanks in advance.
use extend
var object = $.extend({}, object1, object2);
by passing an empty object as the target(first) argument you can preserve both the objects if however you want to merge the second object you can do it like
$.extend(object1, object2);
DEMO
Well, once your JSON is fetched and parsed, you can iterate through the properties and add them to a new object. Be careful though, if there are properties with the same name they will be overwritten.
var data1 = '{"foo": 123, "test":"foo"}'; var data2 = '{"bar": 456, "test":"bar"}'; var json1 = JSON.parse(data1); var json2 = JSON.parse(data2); var merged = {}; for(var i in json1) { if (json1.hasOwnProperty(i)) merged[i] = json1[i]; } for(var i in json2) { if (json2.hasOwnProperty(i)) merged[i] = json2[i]; } console.log(merged);
Resulting merged JSON object will be :
{foo: 123, test: "bar", bar: 456}
DEMO
Edit: As 3nigma mentioned, if you're using jQuery you're better of using $.extend
. Don't forget to first pass an empty object if you don't want to modify your existing objects.
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