I am trying to achieve the following result dynamically without manually specifying where the matches are located in the Object's properties.
Intended Result
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!",
},
},
},
}
Current Progress
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, there seems to be a flaw in my code logic where upon exiting the recursion, it overrides the changed values with the original ones.
Is there a way to create a function that achieves the same as the 'Intended Result'?