简体   繁体   English

如何合并两个json对象以获得一个json对象?

[英]How to merge two json objects to get one json object?

I am trying to merge/combine two json objects to get one final json object(merged object). 我正在尝试合并/合并两个json对象以获得一个最终的json对象(合并对象)。 I have tried the fiddle , but I am getting like: [object Object] if I use $.extend and Uncaught TypeError: testjson1.concat is not a function error if I use cancat. 我尝试了小提琴 ,但是我变得像: [object Object]如果我使用$ .extend和Uncaught TypeError: testjson1.concat is not a function如果我使用cancat,则Uncaught TypeError: testjson1.concat is not a function错误。 Please help me how can I get my required json object either using javascript or jquery or angularJS ? 请帮助我如何使用javascript或jquery或angularJS获取所需的json对象?

You might want to convert the JSONs into javascript objects, then perform the merging like so and convert back to JSON. 您可能希望将JSON转换为javascript对象,然后像这样执行合并,然后转换回JSON。

How can I merge properties of two JavaScript objects dynamically? 如何动态合并两个JavaScript对象的属性?

Basically iterate over the keys and assign them. 基本上迭代密钥并分配它们。

var obj1 = JSON.parse(testjson1),
    obj2 = JSON.parse(testjson2)

for (var attrname in obj2) { obj1[attrname] = obj2[attrname] }

var finaljsonresult = JSON.stringify(obj1)

But this is just a sneak peak, you might want to see the linked answer for more information. 但这只是一个潜行高峰,您可能希望查看链接的答案以获取更多信息。

Since this question is tagged with AngularJS , why not convert the JSONs to JavaScript objects using angular.fromJson and then merge them with angular.merge ? 由于这个问题是用AngularJS标记的,为什么不使用angular.fromJson将JSON转换为JavaScript对象,然后将它们与angular.merge合并?

Unlike angular.extend , angular.merge recursively descends into object properties of source objects, performing a deep copy . angular.extend不同,angular.merge递归地下降到源对象的对象属性中, 执行深度复制

 var obj1 = { 'a': 'aa', 'b': 'bb', 'c': 'cc' }, obj2 = { 'a': 'aa', 'd': 'dd', 'e': 'ee' }; for (var key in obj2) { obj1[key] = obj2[key] } var res = JSON.stringify(obj1); alert(res); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

The Extend keyword in jquery making stringify:
  var object1 = { 
                 apple: 0, 
                banana: { weight: 52, price: 100 }, 
                cherry: 97 
                };
        var object2 = {
                         banana: { price: 200 },
                         durian: 100};
        var ss = $.extend(object1, object2);
        alert(JSON.stringify(ss));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM