I have a function that takes an object from a list as a parameter. I create a new instance of this object and make it equal to the object passed into the function. I change some of the properties of the new object, but these changes also get applied to the original object in the list. Example:
public void myFunction(Object original)
{
var copyOfObject = original;
copyOfObject.SomeProperty = 'a';
}
From reading, I guess I am creating a shallow copy of my original object, so when I update the properties on my new object this causes the properties on the original to change to? I've seen some examples of copying the entire list of objects to create a deep copy, but I only want to create a deep copy of this single object and not the entire list. Can I do this without having to do:
copyOfObject = new Object();
copyOfObject.someProperty = original.someProperty;
before making my changes?
assign() method is used to copy all enumerable values from a source object to the target object. Example: const obj = {a:1,b:2,c:3}; const clone = Object. assign({},obj); console.
So everyone needs to copy an object into another variable but we don't need to reference it, we need to create a new object from the copying object. So, on JavaScript & TypeScript languages, we have the option to do that in multiple ways. But we have used the “newObject = {… Object}” thing commonly in typescript.
The Object. assign() method can be used to merge two objects and copy the result to a new target. Just like the spread operator, If the source objects have the same property name, the latter object will replace the preceding object. Now, let's look at another example of merging in Typescript.
You could apply serialize-deserialize for the object to create deep copy.
public static class ObjectExtensions
{
public static T Clone<T>(this T obj)
{
return (T)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(obj));
}
}
Then usage;
public void myFunction(Object original)
{
var copyOfObject = original.Clone();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With