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

JavaScript에서 두 개의 객체 배열을 병합하고 속성 기준으로 중복 데이터 제거하기

두 개의 객체 배열을 하나로 합치면서 특정 속성값을 기준으로 중복되는 데이터를 제거하고 싶다면 map()find() 메서드를 함께 활용하면 됩니다.

map()은 첫 번째 배열의 모든 요소를 순회하며 새로운 배열을 생성하고, find()는 두 번째 배열에서 조건에 일치하는 요소를 찾아 대체하는 역할을 합니다. 이 두 메서드를 조합하면 productId와 같은 고유 키를 기준으로 데이터를 병합할 수 있습니다.

예제 코드

다음은 productId를 기준으로 두 배열을 비교하여 중복된 상품 정보를 교체하는 코드입니다.

var details1 = [
  {
    productDetails: {
      isSold: true,
      productId: 101
    }
  },
  {
    productDetails: {
      isSold: true,
      productId: 103
    }
  }
]

var details2 = [
  {
    productDetails: {
      isSold: false,
      productId: 101
    }
  }
]

var details3 = details1.map(details1Object => {
  var newObject = details2.find(obj =>
    obj.productDetails.productId === details1Object.productDetails.productId)
  return newObject ? newObject : details1Object
})
console.log(details3)

코드 동작 원리

  • map(): details1 배열의 각 객체를 순회하면서 새로운 배열(details3)을 만듭니다.
  • find(): details2 배열에서 현재 순회 중인 객체와 productId가 동일한 객체를 검색합니다.
  • 삼항 연산자: find() 결과가 존재하면 details2의 객체로 교체하고, 존재하지 않으면 원래 객체(details1)를 그대로 유지합니다.

즉, productId가 101인 객체는 details2의 값(isSold: false)으로 덮어써지고, details2에 없는 productId 103 객체는 그대로 남게 됩니다.

프로그램 실행 방법

위 프로그램을 실행하려면 Node.js 환경에서 다음 명령어를 입력합니다.

node fileName.js

여기서는 파일 이름이 demo183.js라고 가정합니다.

출력 결과

프로그램을 실행하면 아래와 같은 결과가 출력됩니다.

PS C:\Users\Amit\javascript-code> node demo183.js
[
  { productDetails: { isSold: false, productId: 101 } },
  { productDetails: { isSold: true, productId: 103 } }
]

결과를 보면 productId가 101인 객체는 details2의 데이터(isSold: false)로 대체되었고, 나머지 객체는 변경 없이 유지된 것을 확인할 수 있습니다. 이처럼 map()과 find()를 조합하면 별도의 외부 라이브러리 없이도 객체 배열 간의 중복 제거 및 병합 작업을 간단하게 처리할 수 있습니다.