It happens a lot that you want to copy a variable, with an Object or Array, to manipulate the data and use it afterward. But when we create an array of users and make a copy in a new variable, like this:
It will keep a reference from “duplicateObject” to “originalObject”. This is also called a shallow copy.
To show you that it will keep its reference, we gonna change the first name of the first user in the “originalObject”.
Then log the “originalObject” and “duplicateObject” and the result will show you that both are changed! In a lot of cases, you don’t want this to happen!!
So how do we fix this?
We can do the trick with JSON.stringify and JSON.parse method.
And if we now change the first name of the first user in the originalObject, the duplicate will not change!
Check it via the console to log the “originalObject” and “duplicateObject”;