Last active
May 1, 2022 22:44
-
-
Save DoctorDerek/179885bbd47946b956e91d22adc7c086 to your computer and use it in GitHub Desktop.
Deep copy with custom function https://medium.com/p/58fa3de25130
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const customDeepCopy = (inObject) => { | |
let outObject, value, key; | |
if (typeof inObject !== "object" || inObject === null) { | |
return inObject; // Return the value if inObject is not an object | |
} | |
// Create an array or object to hold the values | |
outObject = Array.isArray(inObject) ? [] : {}; | |
for (key in inObject) { | |
value = inObject[key]; | |
// Recursively (deep) copy for nested objects, including arrays | |
outObject[key] = customDeepCopy(value); | |
} | |
return outObject; | |
}; | |
// Start with a deeply nested array object: | |
const array = [37, { a: "b" }, { b: { c: "d" } }]; | |
// Make a deep copy with a custom function: | |
const copy = customDeepCopy(array); | |
console.info(array); // [37, {a: "b"}, {b: {c: "d"}}] | |
copy[0] = -0; // Change a primitive value (not nested) | |
copy[1].a = "y"; // Change a deeply nested value | |
copy[2].b.c = "z"; // Change another deeply nested value | |
// Deeply nested objects were actually copied this time: | |
console.info(array); // [37, {a: "b"}, {b: {c: "d"}}] | |
// Note how the changes to copy did not affect array: | |
console.info(copy); // [-0, {a: "y"}, {b: {c: "z"}}] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment