I am looking to recreate the following as seen below, dynamically without having manually define where the matches are in the Object's properties.
Desired Outcome
const obj = {
levelOne: {
someFun: () => {},
levelTwo: {
anArray: [],
something: 'asas',
levelThree: {
stay: 'the same',
name: 'Set this one!',
},
},
},
}
const updatedObj = {
...obj,
levelOne: {
...obj.levelOne,
levelTwo: {
anArray: [],
...obj.levelOne.levelTwo,
levelThree: {
...obj.levelOne.levelTwo.levelThree,
name: 'Updated prop!',
},
},
},
}
console.info(updatedObj)
{
levelOne: {
someFun: () => {},
levelTwo: {
something: 'asas',
levelThree: {
stay: 'the same',
name: "Updated prop!",
},
},
},
}
So far
const inputOriginal = {
levelOne: {
levelTwo: {
something: 'asas',
levelThree: {
name: "Original input!"
}
}
}
}
const newInput = {
levelOne: {
levelTwo: {
levelThree: {
name: "Updated prop!"
}
}
}
}
const mergeObjects = function(overWrite, original){
return Object.entries(original).reduce( (acc, [ key, item ]) => {
if(typeof item === 'object' && overWrite[key]) {
mergeObjects(overWrite[key], item)
acc = {
...acc,
[key]: item
}
} else if(overWrite[key]) {
acc = {
...acc,
[key]: overWrite[key]
}
}
return acc
}, {})
}
const merged = mergeObjects(inputOriginal,newInput) //merged.levelOne.levelTwo.levelThree = "Updated prop!"
However I can see there is an error logic in my code that, when it comes back out of the recursion, it overwrites the changes values with its self, which has the original values.
How can I create a function that will do the same as 'Desired Outcome'?