jQuery 用jquery合并两个json对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8478260/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:34:52  来源:igfitidea点击:

Merge two json objects with jquery

jqueryajaxjsonobjectmerge

提问by echez

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.

提前致谢。

回答by Rafay

use extend

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

演示

回答by Alex Turpin

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. 如果您不想修改现有对象,请不要忘记首先传递一个空对象。

回答by googamanga

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

回答by Chtiwi Malek

You could use merge

你可以使用合并

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