I asked this question before but I am facing a different problem now.
I have these objects:
let oldObj = {
test1: 'valueTest1',
test2: {
inner1: 'valueInner1',
inner2: 'valueInner2',
inner3: {
otherInner1: 'valueOtherInner1',
otherInner2: 'valueOtherInner2'
}
},
test3: 'valueTest3'
};
let newObj = {
test2: {
inner1: 'newValueInner1',
}
}
and using this code:
for (const key of Object.keys(newObj)) {
if (key in oldObj) {
oldObj[key] = newObj[key];
}
}
I get:
{
test1:'valueTest1',
test2: {
inner1: 'newValueInner1'
},
test3:'valueTest3'
}
But I don't want to remove the other properties of the inner objects (inner2, inner3, etc). I would expect this result:
{
test1: 'valueTest1',
test2: {
inner1: 'newValueInner1',
inner2: 'valueInner2',
inner3: {
otherInner1: 'valueOtherInner1',
otherInner2: 'valueOtherInner2'
}
},
test3: 'valueTest3'
}
Is there a way of having a function that does this?
The objects here are just examples, what I want to achieve is to create a function that deep modifies object properties without removing the rest.
For example, if I define newObj as:
let newObj = {
test2: {
inner3: {
otherInner1:'newValueInner1'
}
}
}
I should get:
{
test1: 'valueTest1',
test2: {
inner1: 'valueInner1',
inner2: 'valueInner2',
inner3: {
otherInner1: 'newValueInner1',
otherInner2: 'valueOtherInner2'
}
},
test3: 'valueTest3'
};