Last Updated: February 25, 2016
·
375
· 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;
  array.push(t);
}

You will get :

[{"a":5,"i":4},{"a":5,"i":4},{"a":5,"i":4},{"a":5,"i":4},{"a":5,"i":4}]

instead of:

[{"a":5,"i":0},{"a":5,"i":1},{"a":5,"i":2},{"a":5,"i":3},{"a":5,"i":4}]

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.