Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript에서 객체를 얕은 복사하는 방법 – _.extend() 활용 가이드

Underscore.js는 자바스크립트 라이브러리로, 자바스크립트에서 객체를 얕은 복사(shallow copy)하기 위한 _.extend() 메서드를 제공합니다. 이 메서드는 소스(source) 객체에 있는 모든 속성을 대상(destination) 객체로 복사한 뒤, 대상 객체를 반환합니다. 이때 복사는 값의 완전한 복제(duplication)가 아니라 참조(reference)를 기반으로 이루어진다는 점이 특징입니다.

기본 문법

_.extend(object*);

_.extend()는 하나 이상의 객체를 인자로 받아 이를 얕은 복사합니다. 필요에 따라 원하는 만큼 많은 객체를 전달할 수 있으며, 속성 이름이 중복될 경우 뒤에 오는 객체의 값이 앞선 값을 덮어쓰게 됩니다.

예제 1

다음 예제에서는 서로 다른 세 개의 객체를 얕은 복사하여 하나의 객체로 합친 후 그 결과를 출력합니다.

<html>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
  <script>
    var res = JSON.stringify(_.extend(
      {name: 'Ram', designation: "content developer"},
      {age: 50},
      {salary: 1200000}));
    document.write(res);
  </script>
</body>
</html>

출력 결과

{"name":"Ram","designation":"content developer","age":50,"salary":1200000}

예제 2

이번에는 네 개의 객체를 병합하는 예제입니다. 각 객체가 가진 속성들이 순서대로 하나의 객체로 합쳐지는 것을 확인할 수 있습니다.

<html>
<body>
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/0.10.0/lodash.min.js"></script>
</head>
<body>
  <script>
    var res = JSON.stringify(_.extend(
        {name: 'Ram', designation: "content developer"},
        {age: 50, salary: 1200000},
        {country: "India"}));
    document.write(res);
  </script>
</body>
</html>

출력 결과

{"name":"Ram","designation":"content developer","age":50,"salary":1200000,"country":"India"}

참고: 최신 자바스크립트에서의 대안

ES6(ES2015) 이후에는 별도의 라이브러리 없이도 표준 메서드인 Object.assign()이나 전개 연산자(spread operator)를 사용해 동일한 얕은 복사를 수행할 수 있습니다.

// Object.assign() 사용
var res = Object.assign({}, {name: 'Ram'}, {age: 50});

// 전개 연산자(spread operator) 사용
var res = {...{name: 'Ram'}, ...{age: 50}};

다만 이들 방식 역시 얕은 복사라는 점은 동일합니다. 따라서 중첩된 객체(nested object)의 내부 값까지 독립적으로 복사하려면 깊은 복사(deep copy) 기법을 별도로 적용해야 한다는 점을 유의하세요.