Merge two JSON objects programmatically

删除回忆录丶 提交于 2019-11-29 04:33:06
Johan van de Merwe
function MergeJSON (o, ob) {
      for (var z in ob) {
           o[z] = ob[z];
      }
      return o;
}

This looks a lot like the code from Elliot, but is a bit safer in some conditions. It is not adding a function to the object, which could lead to some syntax problems, when used in with a framework like Extjs or jQuery. I had the problem that it gave me problems in the syntax when used in an event listener. But credits go to Elliot, he did the job.

Use this as following:

a = {a : 1}
b = {b : 2}
c = {c : 3}

x = MergeJSON ( a, b);
x = MergeJSON ( x, c);

result : x  == {a : 1, b : 2, c : 3}

Thank you Elliot

elliot
Object.prototype.merge = (function (ob) {
    var o = this;
    var i = 0;
    for (var z in ob) {
        if (ob.hasOwnProperty(z)) {
            o[z] = ob[z];
        }
    }
    return o;
})

var a = {a:1}
var b = {b:2}

var c = a.merge(b); // === {a:1,b:2}

Also, if you really want to do the results manipulation server-sided, this article seems to give a pretty reasonable walkthrough of the process.

Rather than merge the two results together, I just decided to parse them, then link those two together. In the end there was really no need to merge the two together when they could be easily joined within a database.

If you are up to a client side solution(JavaScript actually) what about trying the "unite" function I have written: http://code.google.com/p/av-jslib/source/browse/js/aV.ext.object.js#36

Diego Gallardo

With Jquery you could do this!

a = $.extend({a:1}, {b:2});

result: Object { a=1,  b=2}

http://api.jquery.com/jQuery.extend/

I'm not sure how you'd merge these things completely, given that there's a lot of extra data in each apart from the results themselves, but if you just want a JavaScript array containing all 16 results, this should work...

var responses = [GetJsonObjectFromThatUriUsingJqueryOrSomething(),
                 GetJsonObjectFromThatOtherUriUsingJqueryOrSomething()];

// Probably want to check for success
// and ensure that responses[i].responseData.results is valid.

var results = [];
for (var i = 0; i < responses.length; ++i)
{
    results = results.concat(responses[i].responseData.results);
}

To make it more neat, you can add the merge function to the JSON object. This is the solution from Johan van de Merwe based on Elliot's answer, added to the actual JSON object.

// Extend JSON object
JSON.merge = function (o,ob) {

  for (var z in ob) {
    o[z] = ob[z];
  }

  return o;
}

json3 = JSON.merge(json1,json2);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!