将两个json对象与jquery合并

时间:2022-08-28 12:13:36

I have two json objects:

我有两个json对象:

http://example.com/search.json?section=saloon

http://example.com/search.json?section=saloon

and

http://example.com/search.json?section=coupe

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.

提前谢谢。

4 个解决方案

#1


49  

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

演示

#2


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.

一旦你的JSON被获取并解析,你就可以遍历属性并将它们添加到一个新对象中。但是要小心,如果有相同名称的属性,它们将被覆盖。

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 :

合并后的JSON对象为:

{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.

编辑:正如3nigma提到的,如果您使用jQuery,您最好使用$.extend。如果不想修改现有对象,请不要忘记先传递一个空对象。

#3


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.

所有这些都覆盖整个对象,即使一个属性不同,如果您想要使用新的属性附加对象,并且只覆盖JSON的叶子,那么使用这个。

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;
}

#4


1  

You could use merge

您可以使用合并

var mergedObj = $.merge(jsonObj1, jsonObj2);

#1


49  

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

演示

#2


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.

一旦你的JSON被获取并解析,你就可以遍历属性并将它们添加到一个新对象中。但是要小心,如果有相同名称的属性,它们将被覆盖。

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 :

合并后的JSON对象为:

{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.

编辑:正如3nigma提到的,如果您使用jQuery,您最好使用$.extend。如果不想修改现有对象,请不要忘记先传递一个空对象。

#3


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.

所有这些都覆盖整个对象,即使一个属性不同,如果您想要使用新的属性附加对象,并且只覆盖JSON的叶子,那么使用这个。

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;
}

#4


1  

You could use merge

您可以使用合并

var mergedObj = $.merge(jsonObj1, jsonObj2);