Last active
August 29, 2015 14:16
-
-
Save Maddix/3946353d67e666e87a29 to your computer and use it in GitHub Desktop.
This function returns a deep copy of a list or object.
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
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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