[javascript] 동적으로 생성된 프로퍼티의 복사와 이동 방법
동적으로 생성된 프로퍼티를 다른 객체로 복사하거나 이동해야 하는 경우가 있습니다. 이를 위해 두 가지 주요 방법을 사용할 수 있습니다: 객체 분해 및 Object.assign() 메서드입니다.
객체 분해
객체 분해를 사용하여 동적으로 생성된 프로퍼티를 다른 객체로 복사할 수 있습니다.
const source = {
key1: 'value1',
key2: 'value2'
};
const { key1, ...remaining } = source;
const destination = { newKey: key1, ...remaining };
console.log(destination);
위 예제에서, source
객체의 key1
을 destination
객체의 newKey
에 복사하고 나머지 프로퍼티들은 remaining
객체로 이동합니다.
Object.assign() 메서드
Object.assign() 메서드를 사용하여 동적으로 생성된 프로퍼티를 다른 객체로 복사할 수 있습니다.
const source = {
key1: 'value1',
key2: 'value2'
};
const destination = {
key3: 'value3'
};
Object.assign(destination, source);
console.log(destination);
위 예제에서, Object.assign() 메서드를 사용하여 source
객체의 프로퍼티를 destination
객체로 복사합니다.
결론
동적으로 생성된 프로퍼티를 다른 객체로 복사하거나 이동하기 위해, 객체 분해 또는 Object.assign() 메서드를 사용할 수 있습니다. 이를 통해 유연하게 객체의 프로퍼티를 복사하고 이동할 수 있습니다.
더 많은 정보는 아래 참고 자료를 확인할 수 있습니다.
- (MDN Web Docs)[https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Object/assign]
- (MDN Web Docs)[https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment]