Home > Web Front-end > JS Tutorial > body text

Shallow vs Deep Copy of Objects in JavaScript

Mary-Kate Olsen
Release: 2024-10-04 22:25:02
Original
482 people have browsed it

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 };


Copy after login

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 };


Copy after login

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 ));


Copy after login

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

The above is the detailed content of Shallow vs Deep Copy of Objects in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template