我面临的情况是我需要将源对象复制到目标对象。我的源和目标对象是嵌套对象。
源对象:
let remoteOptionObject = {
"key1" : "1",
"key2" : "2",
"key3" :{
"key5" : "5"
}
}
目标对象:
let localOptionObject = {
"Key1" : "1",
"Key2" : "2",
"Key3" :{
"Key4": "4",
"key5" : "5"
},
"key6" : "6",
}
预期结果:
let expectedLocalObj= {
"Key1" : "1",
"Key2" : "2",
"Key3" :{
"Key4": "4",
"key5" : "5"
},
"key6" : "6",
}
这里我想保留target的键并仅更新源Object中存在的键。我尝试过使用Object.assign({},target,source},但这是删除嵌套的键(如预期的那样)。
以下是我尝试过的及其工作原理,但这是一种正确的方法。
function assignSourceToTarget(source, target){
for (var property in source) {
if(typeof source[property] === 'object') {
if (!target[property]) Object.assign(target, { [property]: {} });
assignSourceToTarget(source[property], target[property])
} else {
if(source.hasOwnProperty(property)) {
target[property] = source[property]
}
}
}
return target;
}