21

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.

echez
  • 555
  • 3
  • 7
  • 19

5 Answers5

55

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

Rafay
  • 30,950
  • 5
  • 68
  • 101
  • Thanks for the swift response guys, I've got a blank page... still working on it... I am using jquery – echez Dec 12 '11 at 17:44
  • Here's my code: var saloon = "http://example.com/search.json?section=saloon"; var coupe = "http://example.com/search.json?section=coupe"; var obj1 = JSON.parse(saloon); var obj2 = JSON.parse(coupe); var allResults = $.extend({}, obj1, obj2) – echez Dec 12 '11 at 17:49
  • have a look here you can modify it something like this but honestly i couldn't understand what you are trying to do http://jsfiddle.net/juBAc/3/ – Rafay Dec 12 '11 at 17:58
  • sorry you threw me off 3nigma. The two links return data from a json api – echez Dec 12 '11 at 17:58
5

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.

Community
  • 1
  • 1
Alex Turpin
  • 46,743
  • 23
  • 113
  • 145
3

You could use merge

var mergedObj = $.merge(jsonObj1, jsonObj2);
Chtioui Malek
  • 11,197
  • 1
  • 72
  • 69
  • 2
    This does only work well with arrays - and besides it alters the first jsonOb1. For merging objects `$.extend` should be used instead. – acme Apr 30 '14 at 12:14
2

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;
}
googamanga
  • 172
  • 1
  • 8
0

Thanks to Rafay.

Totally works if you want to extend one object in array, here is my example:

$(document).ready(function() {

    $(document).on("click", ".btnClassClose", function () {

        var tinyMCEcontent = tinymce.activeEditor.getContent();
        var getAttrIDArray = [];

        $("#" + getelementId).html("");
        $("#" + getelementId).html(tinyMCEcontent);
        $("#" + getelementId).append(buttonEDI);

        var PageName = new Object();
        PageName["mdlPageContentHtml"] = tinyMCEcontent;
        var getarraylist = JSON.parse($("#" + getelementId).attr('data-atrrib'));



        var obj = $.extend({}, getarraylist, PageName);

        getAttrIDArray.push(obj);
        var contentGetAttrIDArray = SecondMainSendAjax("CMS?handler=Content", getAttrIDArray);
      
    });
});
baikho
  • 5,203
  • 4
  • 40
  • 47
MikeRyz
  • 209
  • 1
  • 3
  • 18