Skip to content

Instantly share code, notes, and snippets.

@Maddix
Last active August 29, 2015 14:16
Show Gist options
  • Save Maddix/3946353d67e666e87a29 to your computer and use it in GitHub Desktop.
Save Maddix/3946353d67e666e87a29 to your computer and use it in GitHub Desktop.
This function returns a deep copy of a list or object.
copyItem = function(item, shallow) {
var itemProto = Object.prototype.toString.call(item);
var newItem = item;
var getItem = function(child) { return !shallow ? copyItem(child) : child; };
if (itemProto === Object.prototype.toString.call([])) {
newItem = [];
for (var itemIndex=0, len=item.length; itemIndex < len; itemIndex++) newItem.push(getItem(item[itemIndex]));
}
if (itemProto === Object.prototype.toString.call({})) {
newItem = {};
for (var itemIndex in item) newItem[itemIndex] = getItem(item[itemIndex])
}
return newItem;
}
@Maddix
Copy link
Author

Maddix commented Mar 6, 2015

I changed the for-loop for arrays, as according to this StackOverflow answer arrays shouldn't be iterated using the for-in statment.

http://stackoverflow.com/questions/3010840/loop-through-array-in-javascript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment