使用Lodash的mergeWith方法将两个对象合并,而不是使用_.set方法。
示例代码:
const _ = require('lodash');
let obj1 = {
a: {
b: {
c: 1
}
}
};
let obj2 = {
a: {
d: 2
}
};
let mergedObj = .mergeWith(obj1, obj2, (objValue, srcValue) => {
if (.isObject(objValue)) {
return _.merge(objValue, srcValue);
}
});
console.log(mergedObj); // { a: { b: { c: 1 }, d: 2 } }
这样就避免了使用_.set方法时创建空对象的问题。