We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


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;

You need to login to post a comment.