Merge two json objects with jquery

51,067

Solution 1

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

Solution 2

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.

Solution 3

All of these overwrite entire object even if one property is different, if you want to append objects with new properties and overwrite only the leaves of the JSON then use this.

DEMO

//smart not to delete entire object if a property is different, (unlike  $.extend or _.extend)
// {"a":{"b":"c", "e":"f"}},{"a":{"b":"x"}} -> {"a":{"b":"x", "e":"f"}} not {"a":{"b":"x"}}
//obj1 is not effected,
//obj1 values are overwriten at leaves of obj2
//  smartJSONextend({"a":{"b":"c"}},{"a":"d"}) - {"b":"c"} will be "d"

function smartJSONextend(obj1, obj2) {
    //clone
    var mergedObj = JSON.parse(JSON.stringify(obj1));

    (function recurse(currMergedObj, currObj2){
        var key;

        for (key in currObj2) {
            if (currObj2.hasOwnProperty( key )){

                //keep path alive in mergedObj
                if (!currMergedObj[key]){
                    currMergedObj[key] = undefined;
                }

                if ( typeof currObj2[key] === "string" || typeof currObj2[key] === "number" || typeof currObj2[key] === "boolean" ){
                //overwrite if obj2 is leaf and not nested
                    currMergedObj[key] = currObj2[key];
                } else if (typeof currObj2[key] === "object"){
                //obj2 is nested

                    //and currMergedObj[key] is undefined, sync types
                    if (!currMergedObj[key]) {
                        //obj2[key] ifArray
                        if(currObj2[key].length !== undefined){
                            currMergedObj[key] = [];
                        } else {
                            currMergedObj[key] = {};
                        }
                    }
                    recurse(currMergedObj[key], currObj2[key]);
                }
            }
        }
    }(mergedObj, obj2));

    return mergedObj;
}

Solution 4

You could use merge

var mergedObj = $.merge(jsonObj1, jsonObj2);
Share:
51,067
echez
Author by

echez

Updated on December 29, 2020

Comments

  • echez
    echez over 3 years

    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.

  • Alex Turpin
    Alex Turpin over 12 years
    Oh, did not think of that. +1
  • echez
    echez over 12 years
    Thanks for the swift response guys, I've got a blank page... still working on it... I am using jquery
  • echez
    echez over 12 years
    Here's my code: var saloon = "example.com/search.json?section=saloon"; var coupe = "example.com/search.json?section=coupe"; var obj1 = JSON.parse(saloon); var obj2 = JSON.parse(coupe); var allResults = $.extend({}, obj1, obj2)
  • Rafay
    Rafay over 12 years
    have a look here you can modify it something like this but honestly i couldn't understand what you are trying to do jsfiddle.net/juBAc/3
  • echez
    echez over 12 years
    sorry you threw me off 3nigma. The two links return data from a json api
  • acme
    acme about 10 years
    This does only work well with arrays - and besides it alters the first jsonOb1. For merging objects $.extend should be used instead.