使用...
或者Object.assign()
等赋值方式只能进行浅层的对象赋值,如果对象存在多级嵌套,则无法进行合并更新,以下可以使用深度合并:
function mergeDeep(...objects) {
const isObject = obj => obj && typeof obj === 'object';
return objects.reduce((prev, obj) => {
Object.keys(obj).forEach(key => {
const pVal = prev[key];
const oVal = obj[key];
if (Array.isArray(pVal) && Array.isArray(oVal)) {
prev[key] = pVal.concat(...oVal);
}
else if (isObject(pVal) && isObject(oVal)) {
prev[key] = mergeDeep(pVal, oVal);
}
else {
prev[key] = oVal;
}
});
return prev;
}, {});
}
// copy from https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge
样例2:
MergeRecursive = (obj1, obj2) => {
for (const key in obj2) {
try {
// Property in destination object set; update its value.
if (obj2[key].constructor == Object) {
obj1[key] = MergeRecursive(obj1[key], obj2[key]);
} else {
obj1[key] = obj2[key];
}
} catch (e) {
// Property in destination object not set; create it and set its value.
if (obj2[key]) {
// If obj2[key] is undefined, the destination object will be undefined.
// We shouldn't merge the undefined object to destination.
obj1[key] = obj2[key];
}
}
}
return obj1;
}