daily pastebin goal
69%
SHARE
TWEET

Clone

a guest Nov 16th, 2018 105 in 155 days
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function deep_clone(obj) {
  2.     var newObj = {}
  3.     var keys = Object.keys(obj);
  4.     for (var key of keys) {
  5.         if (obj[key] instanceof Object) {
  6.             newObj[key] = deep_clone(obj[key]);
  7.         } else{
  8.             newObj[key] = obj[key];
  9.         }
  10.     }
  11.     return newObj;
  12. }
  13.  
  14. var original = {
  15.     name: 'Jack',
  16.     age: 20,
  17.     rel: {
  18.         new: 20,
  19.         obj: {
  20.             start: 'new'
  21.         }
  22.     }
  23. };
  24.  
  25. var ref = original;
  26. var clone = deep_clone(original);
  27.  
  28. console.log("Original:\t", original);
  29. console.log("Reference:\t", ref);
  30. console.log("Clone:\t\t", clone);
  31.  
  32. original.name = "Stone";
  33. original.rel.new = 10;
  34. original.rel.obj.start = "Start";
  35.  
  36. console.log("Original:\t", original);
  37. console.log("Reference:\t", ref);
  38. console.log("Clone:\t\t", clone);
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top