所以我想在使用 JS 进行 mixin 时防止覆盖共享 key ,所以我们有:
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' } } }
任何人都知道如何做到这一点(最好没有库)。
最佳答案
一个相当幼稚的解决方案,无法处理循环:
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}}}));
关于javascript - 与 JS 的包容性 mixin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56744955/