Posted By

remysharp on 07/24/07


Tagged

object clone


Versions (?)

clone


 / Published in: JavaScript
 

Clones and object (associative array - not arrays). Goes deep.

Required sometimes when you need to keep the original object intact, i.e. when you pass an object in to a function and modify it in the function - the original would change.

  1. function clone(o) {
  2. if(typeof(o) != 'object') return o;
  3. if(o == null) return o;
  4.  
  5. var newO = new Object();
  6.  
  7. for(var i in o) newO[i] = clone(o[i]);
  8.  
  9. return newO;
  10. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: KitSunde on May 29, 2008

Line 2,3 could more effectively be written as: if(typeof(o)!="object"||o==null)return o;

Posted By: laxmanmankala on October 1, 2010

I am getting "Out of stack space" error while executing newO[i] = clone(o[i]);

I am trying to copy a event to new variable for future use in next event.

What can be the workaround? Please advice,

Thanks, Laxman.

Posted By: laxmanmankala on October 1, 2010

I am getting "Out of stack space" error while executing newO[i] = clone(o[i]);

I am trying to copy a event to new variable for future use in next event.

What can be the workaround? Please advice,

Thanks, Laxman.

Posted By: laxmanmankala on October 1, 2010

I am getting "Out of stack space" error while executing newO[i] = clone(o[i]);

I am trying to copy a event to new variable for future use in next event.

What can be the workaround? Please advice,

Thanks, Laxman.

You need to login to post a comment.