Last active
May 13, 2021 10:24
-
-
Save ross-u/7a72e4430e39553646c9cdfa7e451dce to your computer and use it in GitHub Desktop.
Function for deep copying objects and arrays - cloneObject()
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
// Function takes 1 argument which is either an array or an object | |
function cloneObject(arrayOrObject) { | |
let copy; | |
// If the argument is an array, set the value `copy` to be an empty array | |
if (Array.isArray(arrayOrObject)) { | |
copy = []; | |
} else { | |
// Else if the argument is not an array, set the value `copy` to be an empty object | |
copy = {}; | |
} | |
// Loop over the array or object argument and get every key | |
for(let key in arrayOrObject) { | |
// If the property is an object or array, recursively call the function again | |
// passing that object or array as it's argument | |
if(typeof(arrayOrObject[key]) === "object" && arrayOrObject[key] !== null ){ | |
copy[key] = cloneObject(arrayOrObject[key]); | |
} else { | |
// Else if the value is a primitive, copy the value by assinging it with `=` to the `copy` object/array | |
copy[key] = arrayOrObject[key]; | |
} | |
} | |
return copy; | |
} | |
let original = { | |
name: 'Sarah', | |
age: 35, | |
family: [ | |
{ name: 'Mark', age: 29 }, | |
{ name: 'Linda', age: 33 } | |
] | |
} | |
let clonedObject = cloneObject(original); | |
console.log(original); | |
console.log(clonedObject); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment