1

I am getting output is 5 but I was assuming 3. what is the logic behind and how can I make output 3.

const obj = {
  a: 1,
  b: 2,
  c: {
    p: 3
  }
}
const obj1 = { ...obj}
obj.c.p = 5

console.log(obj1.c.p)
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • 1
    Start off by evaluating why you thought the answer should be 3. (hint: you copied a _reference_ to `c` not the value of it) – Jamiec Sep 21 '21 at 11:47
  • 1
    `obj.c.p` is a reference, not an actual value. When you spread `obj` onto `obj1` the reference to `obj.c.p` is maintained, not the value, so when you do `obj.c.p = 5`, that value is updated, and `obj1` contains a reference to that value. – nbokmans Sep 21 '21 at 11:47

2 Answers2

5

The above only clones the first level, so changing obj's deep attribute will change the reference in obj1

const obj = {
  a: 1,
  b: 2,
  c: { p: 3 }
};

const obj1 = { ...obj, c: {...obj.c} };
obj.c.p = 5;

console.log(obj1.c.p);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

obj spreaded to obj1 but object in c property stays same, e.g. c is a same object. Can deeply clone object like this

const obj1 = JSON.parse(JSON.stringify(obj))