为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

宝慕林4294392 2019-11-18 18:21:29
尝试查看是否有任何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} }‍
查看完整描述

3 回答

?
德玛西亚99

TA贡献1770条经验 获得超3个赞

你想深入扩展


$.extend(true, {}, x, y);

请参阅jQuery.extend([ deep ],target,object1 [,objectN ])的文档


查看完整回答
反对 回复 2019-11-18
?
烙印99

TA贡献1829条经验 获得超13个赞

不依赖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;

}


查看完整回答
反对 回复 2019-11-18
  • 3 回答
  • 0 关注
  • 638 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信