因此,在使用JS进行混合时,我想防止覆盖共享密钥,所以我们有:
const v = {
a: {
b: {
c: 4,
d: 'str'
}
}
};
console.log(Object.assign({}, v, {a: {b: {c: 5}}}));
这将记录:
{a:{b:{c:5}}}
但是我正在寻找这个:
{a:{b:{c:5,d:'str'}}}
任何人都知道该怎么做(最好没有图书馆)。
答案 0 :(得分:0)
一个天真的解决方案,无法处理周期:
const mixin = (a, b) => {
for (let [key, val] of Object.entries(b)) {
if (typeof val !== 'object') {
a[key] = b[key];
continue;
}
if (val === null) {
a[key] = b[key];
continue;
}
if (!a.hasOwnProperty(key)) {
a[key] = b[key];
continue;
}
mixin(a[key], b[key]);
}
return a;
};
const mixinInclusive = (...v) => {
return v.reduce(mixin, {});
};
console.log(mixinInclusive(v, {a: {b: {c: 5}}}));