Copy Object in JavaScript

Different ways to copy object in JavaScript:

1) shallow copy

Shallow copy keeps references to original objects, arrays or functions within the new object, so the "copy" is still linked to the original object. In other words, they will be pointing to the same memory location.

In jQuery

var newObj = $.extend({}, oldObj);

In JavaScript

function shallowCopy(oldObj) {
    var newObj = {};
    for(var i in oldObj) {
        if(oldObj.hasOwnProperty(i)) {
            newObj[i] = oldObj[i];
        }
    }
    return newObj;
}

2) Deep copy

Deep copy duplicates everything, and allocates memory in a different location.

In jQuery

var newObj = $.extend(true, {}, oldObj);

In JavaScript

function deepCopy(oldObj) {
    var newObj = oldObj;
    if (oldObj && typeof oldObj === 'object') {
        newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
        for (var i in oldObj) {
            newObj[i] = deepCopy(oldObj[i]);
        }
    }
    return newObj;
}

3) Mix-ins

Copy from any number of objects and mix them all into a new object.

function mix() {
    var i, j, newObj = {};
    for(i = 0; i < arguments.length; i++) {
        for(j in arguments[i]) {
            if(arguments[i].hasOwnProperty(j)) {
                newObj[j] = arguments[i][j];
            }
        }
    }
    return newObj;
}

Note:
In jQuery, $.clone() method only clones DOM elements.

Yang Zhao

Read more posts by this author.


Comment