Merge two JSON objects programmatically

后端 未结 8 1010
被撕碎了的回忆
被撕碎了的回忆 2020-12-17 02:01

I have two JSON objects here, generated through the Google Search API. The URL\'s of these objects can be found below.

http://ajax.googleapis.com/ajax/services/searc

8条回答
  •  不知归路
    2020-12-17 02:23

    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

提交回复
热议问题