How do you clone an object? Javascript object clone

Telegram Join Our Telegram Channel

Javascript object clone

var obj = {a: 1 ,b: 2}
var objclone = Object.assign({},obj);

Now the value of objclone is {a: 1 ,b: 2} but points to a different object than obj.

Note the potential pitfall, though: Object.assign() will just do a shallow copy, not a deep copy. This means that nested objects aren’t copied. They still refer to the same nested objects as the original:

let obj = {
    a: 1,
    b: 2,
    c: {
        age: 30
    }
};

var objclone = Object.assign({},obj);
console.log('objclone: ', objclone);

obj.c.age = 45;
console.log('After Change - obj: ', obj);           // 45 - This also changes
console.log('After Change - objclone: ', objclone); // 45
Telegram Join Our Telegram Channel

8 Responses

Leave a Reply

Your email address will not be published. Required fields are marked *

Telegram Join Our Telegram Channel

Most Viewed

Monthly Best Selling Templates

Check the latest products added to the marketplace. Fresh designs with the finest HTML5 CSS3 coding.