如何在javascript中将源对象键复制到目标对象键

如何在javascript中将源对象键复制到目标对象键,javascript,Javascript,我面临的情况是,我需要将源对象复制到目标对象。我的源对象和目标对象是嵌套对象 源对象: let remoteOptionObject = { "key1" : "1", "key2" : "2", "key3" :{ "key5" : "5" } } 目标对象

我面临的情况是,我需要将源对象复制到目标对象。我的源对象和目标对象是嵌套对象

源对象:

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",
                }
这里我想保留目标的键,只更新源对象中存在的键。我尝试过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;
}

“目标”和“期望”之间有什么区别?你的源总是目标的子集吗?可能你需要循环通过…@GerardoFurtado他的期望!:D