• support@answerspoint.com

What is the most efficient way to clone an object?

1696

I've seen obj = eval(uneval(o)); being used, but that's currently Firefox-only. In Mootools 1.2, I've done things like obj = BUTS.decode(BUTS.encode(o)); but question the efficiency.

I've also seen recursive copying functions with various flaws. I'm surprised no canonical solution exists.

2Answer


0

I want to note that the .clone() method in jQuery only clones DOM elements. In order to clone JavaScript objects, you would do:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

More information can be found in the jQuery documentation.

I also want to note that the deep copy is actually much smarter than what is shown above – it's able to avoid many traps (trying to deep extend a DOM element, for example). It's used frequently in jQuery core and in plugins to great effect.

  • answered 8 years ago
  • Sandy Hook

0

There doesn't seem to be an in-built one, you could try:

function clone(obj) {
    if(obj === null || typeof(obj) !== 'object' || 'isActiveClone' in obj)
        return obj;

    var temp = obj.constructor(); // changed

    for(var key in obj) {
        if(Object.prototype.hasOwnProperty.call(obj, key)) {
            obj['isActiveClone'] = null;
            temp[key] = clone(obj[key]);
            delete obj['isActiveClone'];
        }
    }    

    return temp;
}
  • answered 8 years ago
  • G John

Your Answer

    Facebook Share        
       
  • asked 9 years ago
  • viewed 1696 times
  • active 9 years ago

Best Rated Questions