Learn JavaScript
Copying Objects
38.6
Lesson

Copy Nested Objects

Sometimes objects have properties that are references to other objects. In such cases, it is not enough to clone the object by iterating over all its properties.

In the example given below, the user and userClone reference the same property name.

Here, changing the firstName property using the userClone object also changes it in the user object. This is because the name and status properties of user are references to other objects.

We can use the JSON.stringify and JSON.parse methods to clone an object that has nested objects as its properties.

In the example given above, the JSON.stringify method converts the user object into a JSON string. Then, the JSON.parse method converts the JSON string back into an object.

When we make changes in the firstName property using userClone, the changes are not visible in the user object.