Alejandro Lora Alejandro Lora - 1 year ago 89
Javascript Question

Object.Assign on Composite Object

I'm having problems with references when I try to copy/clone an object into a variable and then, change values of one and don't affect the another one.

I've been having a look into the doc of

method, and I tried what the have for deep clone unsuccessfully.

I created a plnkr in order to express myself better and in case you know how to do it properly.

Code Sample in here

const value = 20.20;
let a = { a: 10 };
let bb = { v: value };
let b = { b: 20, bb: bb };
let c = { c: 30 };
let object1 = { name: 'cloneObject', a, b, c }
let object2 = Object.assign({}, object1);
let object3 = Object.assign({}, object1); = 'it works fine'; = 999; // this will change same property in object2 & object3 and it shouldn't

document.getElementById('expected1').innerHTML =;
document.getElementById('expected2').innerHTML = value;
document.getElementById('expected3').innerHTML = value;

document.getElementById('name1').innerHTML =;
document.getElementById('name2').innerHTML =;
document.getElementById('name3').innerHTML =;

document.getElementById('value1').innerHTML =;
document.getElementById('value2').innerHTML =;
document.getElementById('value3').innerHTML =;

<table style="width:100%; text-align: center">




<th>Expected Value</th>
<td>Object 1</td>
<td id='name1'></td>
<td id='value1'></td>
<td id='expected1'></td>
<td>Object 2</td>
<td id='name2'></td>
<td id='value2'></td>
<td id='expected2'></td>
<td>Object 3</td>
<td id='name3'></td>
<td id='value3'></td>
<td id='expected3'></td>

After @czosel answer, I'm going to use this


So it would looks like this:

let object1 = {name: 'cloneObject', a, b, c}
let object2 = JSON.parse(JSON.stringify(object1));
let object3 = JSON.parse(JSON.stringify(object1));

Answer Source

Object.assign doesn't do deep cloning, see Warning for Deep Clone (MDN).

For alternatives, please see this popular question.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download