Last active
August 29, 2015 14:21
-
-
Save orioltf/9a58a3ec99b118c8130d to your computer and use it in GitHub Desktop.
#JS #UTIL Clone objects
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
/** | |
* In JavaScript assigning an Object to a new variable creates a reference to the original object. This means that changes to an element from the original object will be reflected on the new variable too. This util effectively duplicates a given Object/Array. Drawback: this action will increase the memory usage from your application. | |
* @param {Object|Array} source - the source object or Array to be duplicated. | |
* @returns {Object|Array} either the duplicated Object/Array or the original source element if it is neither an Object nor an Array. | |
*/ | |
var clone = function(source) { | |
var copy, i; | |
if (Object.prototype.toString.call(source) === '[object Array]') { | |
copy = []; | |
for (i=0; i<source.length; i++) { | |
copy[i] = clone(source[i]); | |
} | |
return copy; | |
} else if (typeof(source) === 'object') { | |
copy = {}; | |
for (var prop in source) { | |
if (source.hasOwnProperty(prop)) { | |
copy[prop] = clone(source[prop]); | |
} | |
} | |
return copy; | |
} else { | |
return source; | |
} | |
}; |
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
/ userBooks is a variable already set. | |
var userBooksClone = clone(userBooks); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment