I am facing a situation where I need to copy source object to target object. My source and target objects are nested object.
source object :
let remoteOptionObject = {
"key1" : "1",
"key2" : "2",
"key3" :{
"key5" : "5"
}
}
target object:
let localOptionObject = {
"Key1" : "1",
"Key2" : "2",
"Key3" :{
"Key4": "4",
"key5" : "5"
},
"key6" : "6",
}
expected result :
let expectedLocalObj= {
"Key1" : "1",
"Key2" : "2",
"Key3" :{
"Key4": "4",
"key5" : "5"
},
"key6" : "6",
}
Here I want to retain the keys of target and update only those which are present in source Object. I have tried with Object.assign({}, target, source} but that is removing keys which are nested (as expected).
Below is what I have tried and its working but is this a correct approach.
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;
}