合并两个对象并忽略唯一键

时间:2017-03-15 09:18:07

标签: javascript node.js

我有两个对象originalcustom。我想将custom合并到original,但忽略original对象中未找到的来自custom的密钥。例如:

var original = {

    coupon: {
            coupon: "Coupon",
            couponTypes: {
                single: "Single",
            }
        },

    language: {
            Language: "Language",
            chooseLanguage: "Choose your language",
            }

        }


 var custom = {

    coupon: {
        coupon: "Coupon Details",
        couponTypes: {
            single: "Single Coupon",
        }
    }   
}

预期结果应如下:

 var result = {

     coupon: {
            coupon: "Coupon",
            couponTypes: {
                single: "Single",
            }
        }   
    }

它应该仅替换自定义对象中存在的那些键的值,而忽略另一个。

1 个答案:

答案 0 :(得分:1)

解决此类问题的常用方法是递归:



var def={coupon:{coupon:"Coupon",couponTypes:{single:"Single"}},language:{Language:"Language",chooseLanguage:"Choose your language"}},
    custom={coupon:{coupon:"Coupon Details",couponTypes:{single:"Single Coupon"}}};

function merge(a, b) {
  var c = {};
  for (var k in a) {
    if (k in b) c[k] = typeof b[k] === "object" ? merge(a[k], b[k]) : b[k];
  }
  return c;
}

console.log(merge(custom, def));