2

I looked in the js docs and while studying the doc it mentioned in object.assign() If the source value is a reference to an object, it only copies the reference value.

In my below snippet, one alters the original object and the other doesn't

    var objA = {
    a: 1,
    b: {
       c: 2,
       d: {
       e: 3,
     },
    },
  } 
var objC = { t: 1 };

  //why this works i.e adds a to objEmpty
// var objEmpty = Object.assign({}, { objC });  //this would add a prop to the objEmpty object

//this doesnt work i.e doesnt add a to objEmpty
var objEmpty = Object.assign({}, objC);  //this will not
objC.a = 3;

console.log(objC);

console.log(objEmpty);

I am getting my head around how really things work by trying different scenarios and I believe that it is something related to reference but how?

Another example from the docs

  const obj2 = Object.assign({}, obj1);
  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

  obj1.a = 1;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
  console.log(JSON.stringify(obj2)); // { "a": 0, "b": { "c": 0}}

  obj2.a = 2;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 0}}
  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 0}}
  obj2.b.c = 3;
  console.log(JSON.stringify(obj1)); // { "a": 1, "b": { "c": 3}}
  console.log(JSON.stringify(obj2)); // { "a": 2, "b": { "c": 3}}```

why does js behave this way? why the 3 got changed but the other didn't?

Thanks in advance :)
1

1 Answer 1

2

why does js behave this way? why the 3 got changed but the other didn't?

Because Object.assign() actually does Shallow Copy, you need to do Deep Copy

To do deep copy of an object.

There are bunch of ways, The most common and popular way is to use JSON.stringify() with JSON.parse().

const oldObj = {a: {b: 1}, c: 2};
const newObj = JSON.parse(JSON.stringify(oldObj));
oldObj.a.b = 3; // will not affect the newObj
console.log('oldObj', oldObj);
console.log('newObj', newObj);

Note: There's a new JS standard called structured cloning. It works on all browsers:

method creates a deep clone of a given value using the structured clone algorithm.

const clone = structuredClone(object);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.