Object合并,并使用默认值处理
private mergeObject(targetObj: any, sourceObj: any, defaultObj: any) {
if (defaultObj instanceof Object) {
let keys = Object.keys(defaultObj);
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
const prop = defaultObj[key]
if (prop instanceof Array || prop instanceof Object) {
if (targetObj[key] == undefined) {
targetObj[key] = prop instanceof Array ? [] : {};
}
this.mergeObject(targetObj[key], sourceObj[key], defaultObj[key]);
} else {
if (sourceObj && sourceObj[key]) {
targetObj[key] = sourceObj[key];
} else {
targetObj[key] = defaultObj[key];
}
}
}
} else if (defaultObj instanceof Array) {
defaultObj.forEach(targetSubObj => {
this.mergeObject(targetSubObj, sourceObj, defaultObj);
});
}
}
本文来自博客园,作者:广林,转载请注明原文链接:https://www.cnblogs.com/guanglin/p/14654745.html