programing

Angular의 객체를 복사합니다.

codeshow 2023. 10. 14. 10:45
반응형

Angular의 객체를 복사합니다.

AngularJS 가 가지고 있습니다.angular.copy()객체 및 배열을 심층 복사합니다.

앵귤러도 그런 거 있어요?

다음을 사용할 수도 있습니다.

JSON.parse(JSON.stringify(Object))

사용자 범위에 있다면 모든 Angular 구성요소, 지시사항 등에 해당되며 모든 노드 환경에도 해당됩니다.

원형 참조가 없는 한, 이 참조는 작동해야 하며 원래 개체에 대한 변수 참조를 효과적으로 분리합니다.

또 다른 옵션은 독자적인 기능을 구현하는 것입니다.

/**
 * Returns a deep copy of the object
 */
public static deepCopy(oldObj: any) {
    var newObj = oldObj;
    if (oldObj && typeof oldObj === "object") {
        if (oldObj instanceof Date) {
           return new Date(oldObj.getTime());
        }
        newObj = Object.prototype.toString.call(oldObj) === "[object Array]" ? [] : {};
        for (var i in oldObj) {
            newObj[i] = this.deepCopy(oldObj[i]);
        }
    }
    return newObj;
}

이 질문은 angular 2에서 angular.copy를 사용하는 방법을 중복하는 질문이 아닙니다. 왜냐하면 OP에서 deep copy 객체에 대해 묻기 때문입니다.연결된 답변은 깊은 복사본을 만들지 않는 Object.assign()을 추천합니다.

실제로 Angular2를 사용해도 $.clone() 함수를 사용하는 객체나 _.cloneDeep()을 사용하는 lodash를 사용하는 경우 jQuery와 같은 다른 라이브러리를 사용할 수 없습니다.

대부분의 라이브러리는 타이핑 CLI 도구를 통해 타이핑을 사용할 수 있기 때문에 타이핑 스크립트에서 변환할 때에도 원하는 모든 것을 원활하게 사용할 수 있습니다.

참고 항목:자바스크립트에서 객체를 딥클론하는 가장 효율적인 방법은 무엇입니까?

넌 할 수 있다.deep copylodash의 cloneDeep 메서드를 사용하여 Angular에 있는 개체:

로대시 설치yarn add lodash아니면npm install lodash.

구성 요소에서 가져오기cloneDeep사용:

import * as cloneDeep from 'lodash/cloneDeep';
...
clonedObject = cloneDeep(originalObject);

당신의 빌드에 18kb가 추가된 것에 불과하므로 이점을 누릴 가치가 있습니다.

lodash의 클론 Deep을 사용하는 이유에 대해 더 많은 통찰력이 필요하다면 여기에 기사도 작성했습니다.

Create helper class with name deepCopy.ts

/*
* DeepCopy class helps to copy an Original Array or an Object without impacting on original data
*/

export class DeepCopy {

  static copy(data: any) {
    let node;
    if (Array.isArray(data)) {
      node = data.length > 0 ? data.slice(0) : [];
      node.forEach((e, i) => {
        if (
          (typeof e === 'object' && e !== {}) ||
          (Array.isArray(e) && e.length > 0)
        ) {
          node[i] = DeepCopy.copy(e);
        }
      });
    } else if (data && typeof data === 'object') {
      node = data instanceof Date ? data : Object.assign({}, data);
      Object.keys(node).forEach((key) => {
        if (
          (typeof node[key] === 'object' && node[key] !== {}) ||
          (Array.isArray(node[key]) && node[key].length > 0)
        ) {
          node[key] = DeepCopy.copy(node[key]);
        }
      });
    } else {
      node = data;
    }
    return node;
  }
}

필요할 때마다 deepCopy 파일을 가져와 아래 코드와 같이 사용합니다. DeepCopy.copy(arg); , Here arg는 원하는 객체 또는 배열입니다.

KrishnamrajuK의 답변에 대한 몇 가지 수정 사항

export class DeepCopy {
  static copy(data: any, objMap?: WeakMap<any, any>) {
    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;
  }
}

소스가 객체 배열인 경우 맵을 사용합니다.

let cloned = source.map(x => Object.assign({}, x));

오어

let cloned = source.map((x) => {
                return { ...x };
             });

여기에 있는 답들 중 일부는lodash다음과 같은 경고 메시지와 함께 angular 10+로 가져오면 문제가 발생할 수 있습니다.

WARNING in xxxxx.ts depends on lodash/cloneDeep. CommonJS or AMD dependencies can cause optimization bailouts.

다른 답변들은 JSON을 통한 파싱을 사용하거나 그들만의 구현을 롤링하려고 시도합니다.우리 것을 굴리기 위해서가 아니라, 우리는clone: 의존성이 제한된 경량 클론 유틸리티

사용하기 위해서는clone, 이 두 개의 패키지를 설치하기만 하면 됩니다.

npm install clone
npm install --save-dev @types/clone

클론 API를 사용하는 서비스 생성(서비스는 필수는 아니지만 이 접근 방식이 좋습니다):

import { Injectable } from '@angular/core';
import * as clone from 'clone';

@Injectable()
export class ObjectCloneService {
    public cloneObject<T>(value: T): T {
        return clone<T>(value);
    }
}

서비스를 모듈에 추가해야 합니다.

저는 가능한 모든 입력을 수용하고 해당 객체의 심층 복제 사본을 제공하는 매우 간단한 함수를 타이프스크립트로 만들었습니다.

누군가에게 도움이 되길 바랍니다.

  public deepCopy(obj) {

    var clonedObject: any;

    if (obj instanceof Array) {
        var itemArray = Object.assign([], obj);
        clonedObject = itemArray;

        for (var j = 0; j < clonedObject.length; j++) {
            clonedObject[j] = this.deepCopy(clonedObject[j]);
        }

        return clonedObject;
    }
    else if (typeof obj === 'number' || typeof obj == 'string') {
        return obj
    }
    else {


        var item = Object.assign({}, obj);
        clonedObject = item;

        let allKeys = Object.keys(clonedObject);

        for (var i = 0; i < allKeys.length; i++) {
            if (clonedObject[allKeys[i]] instanceof Array) {
                //If the calue is Array
                clonedObject[allKeys[i]] = this.deepCopy(clonedObject[allKeys[i]]);
            }
            else if (clonedObject[allKeys[i]] instanceof Date) {
                clonedObject[allKeys[i]] = new Date(clonedObject[allKeys[i]].valueOf());
            }
            else if (clonedObject[allKeys[i]] instanceof Object){
                //if the value is JOBJECT.
                clonedObject[allKeys[i]] = this.deepCopy(clonedObject[allKeys[i]]);
            }
        }
        return clonedObject;
    }


}

deep copy.angular.copy({}, factory)와 angular의 문제에 직면해 있습니다.extend ({}, factory)은 배열이나 해시 개체에 도움이 되지만 개체를 복사할 때 연결된 종속성에 문제가 있을 수 있습니다.이 문제를 해결했습니다.

 copyFactory = (() ->
    resource = ->
      resource.__super__.constructor.apply this, arguments
      return
    this.extendTo resource
    resource
  ).call(factory)

이것을 시도해 볼 수 있습니다: https://www.npmjs.com/package/ngx-scv-util

저는 같은 문제에 직면했고, 같은 문제에 대한 npm 패키지를 만들었습니다.단지 이 기능에 대한 오버헤드인 것을 알고 있습니다 :) . 시간이 지남에 따라 이 패키지에 더 많은 것을 추가할 계획입니다.이 제품은 Angular의 10.1.6 버전에서 테스트되었습니다.10.1.6 이상 버전에서는 확실히 작동해야 합니다.사용내역은 npm 패키지 페이지에 기재되어 있습니다.

"공통"이 없는 cloneDeep을 사용하려면 다음과 같이 하십시오.JS 또는 AMD 의존성으로 인해 최적화 구제금융이 발생할 수 있습니다.", 다음과 같이 사용할 수 있습니다.

npm i lodash-es --save

그런 다음 단순히 어떤 구성요소에서도:

import { cloneDeep } from 'lodash-es';
// ...
let a = cloneDeep(b);

언급URL : https://stackoverflow.com/questions/36124363/deep-copying-objects-in-angular

반응형