Skip to main content

Creating new objects without referencing the original object in TypeScript

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

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

We have used “newObject = {…Object}” commonly in typescript, and as I found, 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 without any issues and it will create a new object without any reference to the first object.

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 shown below;

let customUser2 = {…user2}

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

 

The issue is if, for an instance, if we changed the name, it’ll only change 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. 😊


LEAVE A COMMENT







POST COMMENTS


© 2021 Creative Software. All Rights Reserved | Privacy | Terms of Use