Combine or merge JSON on node.js without jQuery

后端 未结 18 1998
醉话见心
醉话见心 2020-12-07 17:17

I have multiple JSON like those

var object1 = {name: \"John\"};
var object2 = {location: \"San Jose\"};

They are not nesting o

18条回答
  •  抹茶落季
    2020-12-07 17:58

    The below code will help you to merge two JSON object which has nested objects.

    function mergeJSON(source1,source2){
        /*
         * Properties from the Souce1 object will be copied to Source2 Object.
         * Note: This method will return a new merged object, Source1 and Source2 original values will not be replaced.
         * */
        var mergedJSON = Object.create(source2);// Copying Source2 to a new Object
    
        for (var attrname in source1) {
            if(mergedJSON.hasOwnProperty(attrname)) {
              if ( source1[attrname]!=null && source1[attrname].constructor==Object ) {
                  /*
                   * Recursive call if the property is an object,
                   * Iterate the object and set all properties of the inner object.
                  */
                  mergedJSON[attrname] = zrd3.utils.mergeJSON(source1[attrname], mergedJSON[attrname]);
              } 
    
            } else {//else copy the property from source1
                mergedJSON[attrname] = source1[attrname];
    
            }
          }
    
          return mergedJSON;
    }
    

提交回复
热议问题