자바 스크립트에서 객체를 복사/복제하는 방법

7937 단어 javascript
매우 일반적인 작업은 개체를 복사하는 것입니다. 자바스크립트에서 객체를 복사하는 방법에는 여러 가지가 있으며 데이터 유형에 대한 실행 속도와 제한 사항이 다릅니다.

여기서 함정은 값 대신 참조로 복사하거나 깊은 복사 대신 얕은 복사를 만드는 것이 좋습니다. 왜요? 글쎄, 내가 조금 설명하겠습니다. 🤓

깊은 복사 대 얕은 복사

  • Deep Copy: Copying by value would result in two unrelated objects with same value.
  • Shallow Copy: Copying by reference means that you have two objects that point to the same data in memory.

If you make a shallow copy of object A to object B, and you change any value in the object B it will also manipulate the object A, since it points to the same reference. If the copied data is a primitive it will copy the value.

A shallow copy successfully copies primitive data types, but any object will not be recursively copied, instead the reference will copied.

A deep copy creates a copy of primitive (Boolean, String, Number, BigInt, Symbol) and structural data types (Abjects, Array, Map, Set, Weakmap,...). MDN docs provide a great reference for data types .

💰: Start your cloud journey with $100 in free credits with DigitalOcean!

얕은 복사 개체

When copying/cloning objects the data type of the properties is key to decide what method can be used.

If your object only contains primitive values (numbers, booleans, strings, etc.), you can use the following methods.

  • _.clone (lodash)
  • Object.assign()
  • ... (spread)

_.클론()

The _.clone(value) method from lodash 값의 얕은 복제를 만듭니다. 성능이 좋으며 이미 응용 프로그램에서 타사 라이브러리 lodash를 사용하는 경우 실행 가능한 옵션입니다.

// import lodash
const _ = require('lodash');

const beer = {
  id: 12345,
  name: 'beer',
  icon: '🍺',
  amount: 10,
};

const clonedBeer = _.clone(beer);


Object.assign()

The Object.assign() method copies all enumerable own properties from one or more source objects to a target object. It returns the target object. Object.assign performs a shallow copy of an object.

Syntax: Object.assign(target, ...sources) , see MDN

const beer = {
  id: 12345,
  name: 'beer',
  icon: '🍺',
  amount: 10,
};

const clonedBeer = Object.assign({}, beer);


... (확산)

The spread operator is one of the fastest methods and was introduced with ES6. It's clean and simple and a native method (sorry lodash).

const beer = {
  id: 12345,
  name: 'beer',
  icon: '🍺',
  amount: 10,
};

const clonedBeer = { ...beer };

딥 카피 객체

All methods above create shallow copies of objects. If you have non primitive data types as properties, and you try to make a copy, the object will be copied, BUT the underlying objects will be passed by reference to the new object. This means a shallow copy instead of a deep copy has been created.

There are several methods to create a deep clone.

  • jQuery.extend()
  • JSON - not recommended!
  • _.clonedeep()

jQuery.extend()

If you still use jQuery in your project, you can use the extend jQuery의 메서드입니다.

const obj = {
  name: 'mario',
  food: 'pizza',
};
const objCopy = jQuery.extend(true, [], obj);


JSON 메서드(권장하지 않음)

JavaScript provides native methods for serialization and deserialization, basically to convert most data types to a JSON string, and then a valid JSON string to an object.

IMPORTANT: This method can't be used for copying EVERY object. If the object property (JavaScript) does not have a JSON equivalent, it will be lost in the process of serializing - deserializing.

// This will work
const beerA = {
  id: 12345,
  name: 'beer',
  icon: '🍺',
  amount: 10,
};

const clonedBeerA = JSON.parse(JSON.stringify(beerA));

// This won't work. The function drinkBeer will not be copied and new Date() will be copied as a string.
const beerB = {
  id: 12345,
  name: 'beer',
  icon: '🍺',
  amount: 10,
  date: new Date(),
  drinkBeer: function() {
    this.amount -= 1;
  },
};

const clonedBeerB = JSON.parse(JSON.stringify(beerB));

_.cloneDeep()

The method _.cloneDeep(value) from Lodash does exactly the same thing as _.clone(), except that it recursively clones everything in the object.

// import lodash cloneDeep
const cloneDeep = require('lodash.cloneDeep');

const beer = {
  id: 12345,
  name: 'beer',
  icon: '🍺',
  amount: 10,
  date: new Date(),
  drinkBeer: function() {
    this.amount -= 1;
  },
};

const clonedBeer = cloneDeep(beer);

There are several methods to create a deep clone of an object. I recommend to use Lodash, it's convenient and fast.

프로 팁

Import a single function from Lodash to reduce the size of your dependencies.

const clone = require('lodash.clone');
const clonedeep = require('lodash.clonedeep');

Thanks for reading and if you have any questions , use the comment function or send me a message .

References (and Big thanks): MDN. Resources for developers, by developers , Flavio

Javascript 에 대해 더 알고 싶다면 다음 Javascript Tutorials 을 참조하십시오.

좋은 웹페이지 즐겨찾기