Skip to content

Instantly share code, notes, and snippets.

@ross-u
Last active May 13, 2021 10:24
Show Gist options
  • Save ross-u/7a72e4430e39553646c9cdfa7e451dce to your computer and use it in GitHub Desktop.
Save ross-u/7a72e4430e39553646c9cdfa7e451dce to your computer and use it in GitHub Desktop.
Function for deep copying objects and arrays - cloneObject()

Function for deep copying objects and arrays - cloneObject()


// 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