Tech Insights
Sithum Meegahapola
March 8, 2021

Creating new objects without referencing the original object in TypeScript

Creating new objects without referencing the original object in TypeScript

In this article, I am going to provide a solution to avoid referencingwhen creating a new Object from another Object.

Everyone needs to copy an object into another variable but it isn’tnecessary to reference it. We need to create a new object from the copyingobject. On JavaScript & TypeScript languages, we can do that in multipleways.

We have used “newObject = {…Object}” commonly in typescript, and as Ifound, an issue arises with this method.

Let’s see what it is.

Imagine we have an object with a custom model type created like this:(all the examples are in typescript)

let user: User
user ={name: “”, address: “”, age: “”}

In the above object, we can use the method mentioned previously withoutany issues and it will create a new object without any reference to the firstobject.

let customUser = {…user}

The issue is when we have an object inside the object like this.

let user2: UserData
user2 ={
name:“”, address: “”, age: “”, education: {campus: “”, year: “”, passes: “”}

When we try to copy this to another variable as a new object, without reference to the original object, and if you use the same method as shownbelow;

let customUser2 = {…user2}

it would create a new object and assign values to the new variable butwill create a reference to the object inside that main object. That means therewill be a new copy for the “name, address, age” but the “education” object willbe a reference to the original object.

The issue is if, for an instance, if we changed the name, it’ll onlychange in the new object but if we change the “campus” inside “education” it’ll change in the original object as well.

To avoid this issue, “Deep Cloning” must be done.

let customeUser2 = JSON.stringify(user2)

This will make a new copy of the complete object to the new variable.

But Make sure not to use this “JSON.stringify()” if you have any“functions, undefined, infinity, Regex, Maps, Sets, Blobs, FlieLists,ImageDatas” within your object

And if you do a search on the internet, you will find many ways to do Deep Cloning.

Happy Coding. ?