Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two json objects with jquery

Tags:

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.

like image 214
echez Avatar asked Dec 12 '11 17:12

echez


2 Answers

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

like image 177
Rafay Avatar answered Oct 01 '22 13:10

Rafay


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.

like image 38
Alex Turpin Avatar answered Oct 01 '22 15:10

Alex Turpin