Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Duplicate object in javascript

I see two ways to duplicate objects

1.

var a={c:1}
var b=a;
alert(b.c);//alert 1

2.

var a={c:2};
var b={};
for (i in a)
{b[i]=a[i];} 
alert(b.c);//alert 1

The first are shorter than the second so what is the efficiency in the second example?

like image 681
user1801625 Avatar asked Nov 08 '12 10:11

user1801625


People also ask

How many ways we can clone object in JavaScript?

JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.

How do you deep copy an object in JavaScript?

assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.


1 Answers

In the first version you don't duplicate/clone the object you simply make a extra reference to it:

var a = { a: 1 };
var b = a;
b.a = 2;

console.log(a.a); // 2;

To clone an object there is numbers of libraries that can do that for you:

var b = $.extend({}, a); // Make a shallow clone (jQuery)
var b _.extend({}, a); // Make a shallow clone (underscore.js)

var b = $.extend(true, {}, a); // Make a deep clone (jQuery);

Or you can do it natively:
Simple clone:

var b = {};
var prop;

for (prop in a) {
    b[prop] = a[prop];
}

Scratch of a deep clone function:

function deepClone(obj) {
    var r;
    var i = 0,
    var len = obj.length;
    // string, number, boolean
    if (typeof obj !== "object") { 
        r = obj;
    }
    // Simple check for array
    else if ( len ) { 
        r = [];
        for ( ; i < len; i++ ) {
            r.push( deepClone(obj[i]) );
        }
    } 
    // Simple check for date
    else if ( obj.getTime ) { 
        r = new Date( +obj );
    }
    // Simple check for DOM node
    else if ( obj.nodeName ) { 
        r = obj;
    }
    // Object
    else { 
        r = {};
        for (i in obj) {
            r[i] = deepClone(obj[i]);
        }
    }

    return r;
}
like image 154
Andreas Louv Avatar answered Sep 23 '22 00:09

Andreas Louv