Skip to content

Instantly share code, notes, and snippets.

@kevboutin
Last active Mar 22, 2021
Embed
What would you like to do?
cloning objects in javascript
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);
// Print
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