我有两个对象original
和custom
。我想将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",
}
}
}
它应该仅替换自定义对象中存在的那些键的值,而忽略另一个。
答案 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));