如何通过键合并两个对象值

尝试查看是否有任何JavaScript库功能可以合并两个json对象的特定键的值


var x ={ "student-marks":{'math':1,'physics':5} };

var y ={ "student-marks":{'chemistry':3,'history':2} };

使用$ .extend和$ .merge给出以下结果


$.extend({},x,y)  leads to  { "student-marks":{'chemistry':3,'history':2} }


$.merge(x,y) leads to { "student-marks":{'math':1,'physics':2} }

我正在寻找的是{ "student-marks":{'math':1,'physics':5, 'chemistry':3,'history':2} }‍


宝慕林4294392
浏览 679回答 3
3回答

德玛西亚99

你想深入扩展$.extend(true, {}, x, y);请参阅jQuery.extend([ deep ],target,object1 [,objectN ])的文档

烙印99

不依赖jQuery的简单javascript函数将帮助您合并具有嵌套对象的两个JSON对象。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] = mergeJSON(source1[attrname], mergedJSON[attrname]);          }         } else {//else copy the property from source1            mergedJSON[attrname] = source1[attrname];        }      }      return mergedJSON;}
打开App,查看更多内容
随时随地看视频慕课网APP