Borislav Hadzhiev
Wed Mar 02 2022·2 min read
Photo by Bruno Emmanuelle
To create a deep copy of an object in TypeScript:
JSON.stringify()
method to stringify the object.JSON.parse()
method to parse the string back to an object.const obj = { person: { name: { first: 'James', last: 'Doe', }, address: { country: 'Chile', city: 'Santiago', }, }, }; const copy = JSON.parse(JSON.stringify(obj)) as typeof obj; console.log(copy);
We used the JSON.stringify method to convert the object to a JSON string.
console.log(typeof JSON.stringify({})); // 👉️ "string"
As a result all of the references to nested objects or arrays are lost.
The next step is to parse the JSON string back to an object by using the JSON.parse method.
// 👇️ "object" console.log(typeof JSON.parse(JSON.stringify({})));
At this point we have a deep copy of the original object, but its typed as
any
, so we need to use a
type assertion
to set its type to the type of the original object.
const obj = { person: { name: { first: 'James', last: 'Doe', }, address: { country: 'Chile', city: 'Santiago', }, }, }; const copy = JSON.parse(JSON.stringify(obj)) as typeof obj; console.log(copy);
If you now mutate the copied object, you won't change the contents of the original object.
const obj = { person: { name: { first: 'James', last: 'Doe', }, address: { country: 'Chile', city: 'Santiago', }, }, }; const copy = JSON.parse(JSON.stringify(obj)) as typeof obj; console.log(copy); copy.person.name.first = 'Alice'; console.log(obj.person.name.first); // 👉️ "James"
Changing the value of a property in the copy
object does not change the value
in the original object, because the nested objects and arrays point to different
locations in memory.
To create a deep copy of an object in TypeScript, install and use the
lodash.clonedeep
package. The cloneDeep
method recursively clones a value
and returns the result. The cloneDeep
method returns an object of the correct
type.
Open your terminal in the root directory of your project and install the lodash.clonedeep package with the following 2 commands:
npm i lodash.clonedeep npm i --save-dev @types/lodash.clonedeep
Now we are able to import and use the cloneDeep
method.
import cloneDeep from 'lodash.clonedeep'; const obj = { person: { name: { first: 'James', last: 'Doe', }, address: { country: 'Chile', city: 'Santiago', }, }, }; const copy = cloneDeep(obj); console.log(copy);
The cloneDeep
method takes a value as a parameter, recursively clones it and
returns the result.
You can test changing a value in the copy
object and checking if the value has
changed in the original object.
import cloneDeep from 'lodash.clonedeep'; const obj = { person: { name: { first: 'James', last: 'Doe', }, address: { country: 'Chile', city: 'Santiago', }, }, }; const copy = cloneDeep(obj); copy.person.name.first = 'Alice'; console.log(obj.person.name.first); // 👉️ "James"