Object 복사하기 (JavaScript)

Zoey·2020년 12월 15일

출처: 드림코딩 by 엘리
자바스크립트 7. 오브젝트 넌 뭐니? | 프론트엔드 개발자 입문편 (JavaScript ES6)

// Fun cloning
// Object.assign(dest, [obj1, obj2, obj3...])



const user = { name: 'ellie', age: '20' };
const user2 = user; // user와 user2의 동일한 ref가 같은 object를 가르키고 있다.
user2.name = 'coder';
console.log(user); // {name: "coder", age: "20"}




// 똑같은 reference를 갖는게 아닌,
// object를 복제할 수 있는 방법

// 1. old way
const user3 = {}; // 빈 object를 만들고 나서
for (let key in user) {
  user3[key] = user[key];
}

// 2. new way
const user4 = {};
Object.assign(user4, user);
// 또는
const user5 = Object.assign({}, user);


// another example
const fruit1 = { color: 'red' };
const fruit2 = { color: 'blue', size: 'big' };
const mixed = Object.assign({}, fruit1, fruit2);
// 동일한 프로퍼티를 가진 경우 뒤에 있는 object의 값을 덮어 씌운다.
console.log(mixed.color); // blue
console.log(mixed.size); // big

0개의 댓글