const mainObj = {
};
const valueChanger = (obj) => {
if (!obj.data) {
obj.data = {};
}
return (value) => {
obj.data = { value };
};
};
let current = valueChanger(mainObj);
mainObj.next = {};
let next = valueChanger(mainObj.next);
current(10);
next(20);
console.log('step:1 ', mainObj);
const nextReference = mainObj.next;
_.each(mainObj, (value, key) => delete mainObj[key]);
Object.assign(mainObj, nextReference);
current = next;
current(21);
console.log('step:2 ', mainObj);
.as-console-wrapper { max-height: 100% !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
After setting data in mainObj, Shallow copying next reference into mainObj by using Object.assign(). After that changes of nested object is not reflecting into mainObj.
Actual Result:
{ data: { value: 20 } }
Expected Result:
{ data: { value: 21 } }