orioltf
5/20/2015 - 1:05 PM

#JS #UTIL Clone objects

#JS #UTIL Clone objects

/ userBooks is a variable already set.
var userBooksClone = clone(userBooks);
/**
 * 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;
	}
};