Deep copy an array in Angular 2 + TypeScript

前端 未结 10 1135
温柔的废话
温柔的废话 2020-11-27 04:33

I have an array of objects that is an input. Lets call it content.

When trying to deep copy it, it still has a reference to the previous array.

10条回答
  •  被撕碎了的回忆
    2020-11-27 05:19

    Alternatively, you can use the GitHub project ts-deepcopy, which is also available on npm, to clone your object, or just include the code snippet below.

    /**
     * Deep copy function for TypeScript.
     * @param T Generic type of target/copied value.
     * @param target Target value to be copied.
     * @see Source project, ts-deepcopy https://github.com/ykdr2017/ts-deepcopy
     * @see Code pen https://codepen.io/erikvullings/pen/ejyBYg
     */
    export const deepCopy = (target: T): T => {
      if (target === null) {
        return target;
      }
      if (target instanceof Date) {
        return new Date(target.getTime()) as any;
      }
      if (target instanceof Array) {
        const cp = [] as any[];
        (target as any[]).forEach((v) => { cp.push(v); });
        return cp.map((n: any) => deepCopy(n)) as any;
      }
      if (typeof target === 'object' && target !== {}) {
        const cp = { ...(target as { [key: string]: any }) } as { [key: string]: any };
        Object.keys(cp).forEach(k => {
          cp[k] = deepCopy(cp[k]);
        });
        return cp as T;
      }
      return target;
    };
    

提交回复
热议问题