pbojinov
2/10/2015 - 8:54 PM

Shallow Clone/Copy Javascript Object

Shallow Clone/Copy Javascript Object

/** 
 * Copy by performance (Ranked from best to worst)
 * 
 * Reassignment "=" (for string / number arrays only) // native
 * Slice (for string / number arrays only) // native
 * Concat (for string / number arrays only) // native
 * Custom For-loop Copy // native
 * Object.assign // native
 * $.extend // jQuery
 * JSON.parse // native
 * _.extend() // underscore
 * _.cloneDeep() // lo-dash
 */

var old = {name:'petar'};

// jQuery shallow copy
var clone = jQuery.extend({}, old);

// jQuery Deep copy
var clone = jQuery.extend(true, {}, old);
 
// alternative 
var clone = JSON.parse(JSON.stringify(old));