How to clone an object in JavaScript

In JavaScript the assignation of the objects always is through references, for example:

var ob1 = {a:'hi'};

var ob2 = ob1;

If you print this, It show the following:

console.log(ob1);

console.log(ob2);

{ a: 'hi' }

{ a: 'hi' }

What happend if you modify ob2? For example:

ob2.a = 'hi ob2';

Now I’ll print the value of both of them

console.log(ob1);

console.log(ob2);

The result is:

{ a: 'hi ob2' }

{ a: 'hi ob2' }

The value of both is the same, because the value of ob2 is the reference to ob1,  then how we can have two objects diferents, or exactly how to clone an object?.

That is very simple, you just need convert this object to string and convert it to object again.

var ob1 = {a:'hi'};

var ob2 = JSON.parse(JSON.stringify(ob1));

With this, now you have differents objects, if you modify ob2, this change does not affect to object ob1.

Very simple.

Leave a Reply