Deep Copy, Shallow Copy
I've taken several courses so far and didn't quite understand this, but this time I understood it, so I'm going to write a post about it.
const obj = {
property1: "1",
property2: {
subProperty1: '2-1',
subProperty2: '2-2',
}
}First, I created obj as shown above.
const obj2 = Object.assign({}, obj); //shallow copyNext, I created obj2 and used the Object.assign() function to copy obj into the empty object {}. This is what shallow copy means.
With a shallow copy, changing the value of obj2's property1 has nothing to do with the value in obj. But if you change the value of subProperty1 or subProperty2 in the obj2 object, obj will change too. That's because what was copied isn't the value of the object inside obj but its address.
So what do you do to copy obj completely? That's right, you do a DeepCopy.
const deepCopy = (origin) => {
const result = {};
for (let i in origin) {
if (origin[i] != null && typeof origin[i] === "object") {
result[i] = deepCopy(origin[i]);
} else {
result[i] = origin[i];
}
}
return result;
};Declare the deepCopy function, which takes origin as a parameter. Next, create a result object to hold the result, and in the loop, if the value at key i of origin, the parameter, isn't null or has the form of an object, it repeats through the deepCopy function again. If origin's value isn't an object, it stores the value in result.
This way, you can do a complete DeepCopy.
- #Deep Copy
- #Shallow Copy