Last Updated: February 25, 2016
· vkbalakrishnan

Clone Javascript Objects

If you are doing this :

var temp = {a:5};
var array = [];
for(var i =0; i<5;i++){
  var t = temp;
  t.i = i;

You will get :


instead of:


This is because Javascript uses deep linking when you assign an object to another variable.

My current choice for shallow cloning is Underscore.js clone function.
It is as easy as

var t = _.clone(obj);

Or, you can iterate over the original object and copy all the keys and values.