Javascript Object Cloning Without jQuery

If I really need to clone an object (almost never) I just use jQuery.extend – because someone far better than me wrote the cloning function and I trust them šŸ™‚

However, I recently discovered this nifty littleĀ process that can be used in a pinch. It might be expensive for large operations, but it’ll work on your smaller objects/arrays:

[pastacode lang=”javascript” message=”” highlight=”” provider=”manual”]

var obj2 = JSON.parse(JSON.stringify(obj));

[/pastacode]

So here’s an exploration of thatĀ process compared to something like “.slice(0)” as well:

var arr = [1,2,3];
var arr2 = JSON.parse(JSON.stringify(arr));
arr2.reverse();
var arr3 = arr.slice(0);
arr3.push(5);

console.log(arr);
console.log(arr2);
console.log(arr3);

var str = 1.004;
var str2 = str;
str2 = 2;

console.log(str2);
console.log(str +"1");

var obj = {a: 100};
var obj2 = JSON.parse(JSON.stringify(obj));
obj2.a = 200;

console.log(obj2);
console.log(obj);


See the Pen references by Mike Newell (@newshorts) on CodePen.

 

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.