Serialize and De-serialize
ref – https://dev.to/nas5w/js-fundamentals-object-assignment-vs-primitive-assignment-5h64
One method that can be used to deep copy an object is to serialize and de-serialize the object. One common way to do this is using JSON.stringify and JSON.parse.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
const a = { name: 'Joe', dog: { name: 'Daffodil', }, }; const b = JSON.parse(JSON.stringify(a)); b.name = 'Eva'; b.dog.name = 'Jojo'; console.log(a); // { // name: 'Joe', // dog: { // name: 'Daffodil', // }, // } console.log(b); // { // name: 'Eva', // dog: { // name: 'Jojo', // }, // } |
However, it does not work on function objects:
ref – https://stackoverflow.com/questions/18089033/json-stringify-does-not-process-object-methods