"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Shallow vs Deep Copy of Objects in JavaScript

Shallow vs Deep Copy of Objects in JavaScript

Published on 2024-11-08
Browse:746

Shallow vs Deep Copy of Objects in JavaScript

When we need to copy an object to another object, we generally use something like this:


const mainObject = { id: 1 };
const secondaryObject = { ...mainObject };


But this only works for copying the shallow properties of the object. If we have a case like the following code, the scenario changes:


const mainObject = { id: 1, user: { name: 'John Doe', age: 30 } };
const secondaryObject = { ...mainObject };


The property user won't be copied; it will still be related to mainObject. So, if we alter the user property, it will also affect mainObject. To solve this, we can do the following:


const mainObject = { id: 1, user: { name: 'John Doe', age: 30 } };
const deepCopy = JSON.parse(JSON.stringify(mainObject ));


Now, we have a deep copy of mainObject, with two distinct memory addresses.

Release Statement This article is reproduced at: https://dev.to/claudioguedes/shallow-vs-deep-copy-of-objects-in-javascript-3d2o?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3