Last active
March 22, 2021 18:35
-
-
Save kevboutin/6d27fd9644daed79627e5773632702f4 to your computer and use it in GitHub Desktop.
cloning objects in javascript
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 cloneObject(obj: any): any { | |
switch (obj["constructor"]) { | |
case Date: return new Date(obj); | |
case Object: return Object.keys(obj).reduce<{ [key: string]: any }>((newObj, key) => (newObj[key] = cloneObject(obj[key]), newObj), {}); | |
case Array: return obj.map(cloneObject); | |
} | |
return obj; | |
} | |
// Test | |
const obj = { number: 100, string: "string", boolean: true, object: { key: "value" }, date: new Date(), array: [0] }, | |
objClone = { ...obj }, // spread operator does not copy inner reference keys that hold reference types like object, array, date so are not fully cloned | |
objClone2 = cloneObject(obj); | |
// Update obj | |
obj.number += 1, obj.string += "1", obj.boolean = false, obj.object.key += "1", obj.date.setHours(0), obj.array.push(1); | |
console.log(objClone, objClone2); | |
/** The output here is of variable objClone, which is spread of obj. The reference types of the new object are modified when we modify obj. | |
{ | |
number: 100, string: 'string', boolean: true, | |
object: { key: 'value1' }, // <<< object also updated as this is by reference | |
date: 2021-03-27T18:50:02:0222, // <<< date also updated as this is by reference | |
array: [ 0, 1 ] // <<< array also updated as this is by reference | |
} | |
{ | |
number: 100, string: 'string', boolean: true, | |
object: { key: 'value' }, | |
date: 2021-03-28T13:15:16:0222, | |
array: [ 0 ] | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment