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”;
Read my other posts
Dive into GraphQL w/ Apollo Client by building a SpaceX 🚀 app in Angular 8
I know that this sounds odder than it is, but using GraphQL in an Angular 8 application with Apollo Client feels like…
GraphQL (microservices) architecture by Apollo
GraphQL is fantastic! Apollo build tooling around it to make our life easier, to use it at scale