Advertisement
vit134

Глубокое копирование объекта

Oct 26th, 2018
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*
  2.     Глубокое копирование объекта
  3. */
  4.  
  5. const obj = {
  6.     foo: 'bar',
  7.     bar: 'foo',
  8.     bla: {
  9.         non: 1,
  10.         hui: {
  11.             bla: 'foo',
  12.             bar: 'foo'
  13.         }
  14.     },
  15.     f: function() {return false},
  16.     arr: [
  17.         1,2,3,4,5
  18.     ]
  19. }
  20.  
  21. function deepClone(val) {
  22.   if (Array.isArray(val)) {
  23.     return val.map(deepCopy);
  24.   } else if (typeof val === 'object' && val != null) {
  25.     const obj = {};
  26.     for (const key in val)
  27.       obj[key] = deepCopy(val[key]);
  28.     return obj;
  29.   } else {
  30.     return val;
  31.   }
  32. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement