1

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 } }
0

1 Answer 1

1

Change your valueChanger to

return (value) {
  obj.data.value = value;
};

and it will do what you expect.

Assigning a new object to obj.data breaks the previous reference whereas assigning a new value to the .value property maintains the same obj.data reference which is shared with the parent object.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes @Phil. Until console.log('step:1 ', mainObj); line, If i call current(x) for n times the changes will reflect into mainObj. After shallow copy by using Object.assign(), the reference has been disconnected. Instead of Object.assign(), If we use normal assign mainObj = nextReference, then the problem will be resolved. I don't know exact reason.
@SKumar sorry, I don't understand your comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.