copy object in typescript 1

copy object in typescript

//1.Shallow copy:
let Copy = {...yourObject}
//2.Deep Copy: a. through recusive typing functionality:
let Cone = DeepCopy(yourObject);
public DeepCopy(object: any): any
{
  if(object === null)
  {
    return null;
  }
  const returnObj = {};
  Object.entries(object).forEach(
  ([key, value]) =>{
    const objType = typeof value
  if(objType !== "object" || value === null){
     returnObj[key] = value;
  }
  else{
  	returnObj[key] = DeepCopy(value);
  }
}
//b.Hardway: repeat the following expanstions for all complex types as deep as you need
let Copy = {...yourObject, yourObjsComplexProp: {...yourObject.yourObjsComplexProp}}

Here is what the above code is Doing:
1. Shallow copy:
The first line of code is a shallow copy. It’s a one-liner that creates a new object with the same properties as yourObject.

2. Deep copy:
The second line of code is a deep copy. It’s a one-liner that creates a new object with the same properties as yourObject, and the same properties of yourObject’s properties, and so on.

The deep copy is a recursive function that takes an object as an argument and returns a new object with the same properties.

The function first checks if the object is null. If it is, it returns null.

Then it creates a new object and loops through the object’s properties.

For each property, it checks if the property is an object. If it is, it calls the function again, passing the property as an argument.

If the property is not an object, it adds the property to the new object.

The function returns the new object.

Similar Posts