Skip to content

Instantly share code, notes, and snippets.

@dimabory
Last active November 6, 2018 09:18
Show Gist options
  • Save dimabory/1205f1fd0af3d64ab49850b41d01e3ba to your computer and use it in GitHub Desktop.
Save dimabory/1205f1fd0af3d64ab49850b41d01e3ba to your computer and use it in GitHub Desktop.
The best algorithm for copying objects in Javascript is heavily dependent on the context and type of objects that you are looking to copy
/*
* 1.
* objects with properties which are themselves objects, only the references are copied over:
* var foo = { a: 0 , b: { c: 0 } };
* var copy = { ...foo };
*/
var obj = { foo: "foo", bar: "bar" };
var copy = { ...obj };
var copy = Object.assign({}, obj);
/*
* 2.
* this method only works when the source object contains serializable value types
* and does not have any circular references
*/
var obj = { a: 0, b: { c: 0 } };
var copy = JSON.parse(JSON.stringify(obj));
function deepClone(obj) {
var copy;
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Function
if (obj instanceof Function) {
copy = function() {
return obj.apply(this, arguments);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment