Deep copying objects in Angular

前端 未结 9 2188
悲&欢浪女
悲&欢浪女 2020-12-01 08:58

AngularJS has angular.copy() to deep copy objects and arrays.

Does Angular also have something like that?

9条回答
  •  日久生厌
    2020-12-01 09:19

    Some modifications for KrishnamrajuK's answer

    export class DeepCopy {
      static copy(data: any, objMap?: WeakMap) {
        if (!objMap) {
          // Map for handle recursive objects
          objMap = new WeakMap();
        }
    
        // recursion wrapper
        const deeper = value => {
          if (value && typeof value === 'object') {
            return DeepCopy.copy(value, objMap);
          }
          return value;
        };
    
        // Array value
        if (Array.isArray(data)) return data.map(deeper);
    
        // Object value
        if (data && typeof data === 'object') {
          // Same object seen earlier
          if (objMap.has(data)) return objMap.get(data);
          // Date object
          if (data instanceof Date) {
            const result = new Date(data.valueOf());
            objMap.set(data, result);
            return result;
          }
          // Use original prototype
          const node = Object.create(Object.getPrototypeOf(data));
          // Save object to map before recursion
          objMap.set(data, node);
          for (const [key, value] of Object.entries(data)) {
            node[key] = deeper(value);
          }
          return node;
        }
        // Scalar value
        return data;
      }
    }
    
    

提交回复
热议问题