JavaScript에서 한 배열의 객체 속성을 true 또는 false로 설정하려는 경우, 해당 객체의 id가 다른 객체 배열에 존재하는 id와 일치하는지 확인해야 할 때가 있습니다. 이런 작업은 reduce()와 map() 메서드를 함께 사용하면 간단하게 처리할 수 있습니다.
핵심 아이디어
먼저 reduce()를 사용하여 두 번째 배열의 모든 studentId를 키로 가지는 조회용 객체(lookup object)를 만듭니다. 그다음 map()으로 첫 번째 배열을 순회하면서 각 요소에 matchingResult라는 새로운 속성을 추가합니다. 이때 조회 객체에 해당 id가 있으면 true, 없으면 false가 됩니다.
예제 코드
다음은 전체 코드입니다.
let firstDetails = [
{ "studentId": 101, "studentName": "John" },
{ "studentId": 102, "studentName": "David" },
{ "studentId": 103, "studentName": "Bob" }
]
let secondDetails = [
{ "studentId": 101, "studentName": "Robert" },
{ "studentId": 109, "studentName": "Mike" },
{ "studentId": 103, "studentName": "Adam" }
]
const obj = secondDetails.reduce((o, v) => (o[v.studentId] = true, o), {})
const output = firstDetails.map(v => ({ ...v, matchingResult: obj[v.studentId] || false }))
console.log(output)실행 방법
위 프로그램을 실행하려면 아래 명령어를 사용합니다. 파일 이름은 demo316.js로 저장했다고 가정합니다.
node demo316.js
출력 결과
위 코드를 실행하면 다음과 같은 결과가 출력됩니다.
PS C:\Users\Amit\javascript-code> node demo316.js
[
{ studentId: 101, studentName: 'John', matchingResult: true },
{ studentId: 102, studentName: 'David', matchingResult: false },
{ studentId: 103, studentName: 'Bob', matchingResult: true }
]코드 설명
1단계: reduce()로 조회 객체 생성
secondDetails.reduce((o, v) => (o[v.studentId] = true, o), {}) 부분은 빈 객체 {}를 초기값으로 시작해, 두 번째 배열의 각 요소를 순회하면서 studentId를 키로, true를 값으로 설정합니다. 결과적으로 { 101: true, 109: true, 103: true } 형태의 객체가 만들어집니다.
2단계: map()으로 새 속성 추가
firstDetails.map(...)은 첫 번째 배열의 각 객체를 펼친 뒤(...v), matchingResult 속성을 추가합니다. obj[v.studentId] || false 표현식 덕분에 일치하는 id가 있으면 true, 없으면 undefined 대신 false가 반환됩니다.
이처럼 reduce()와 map()을 조합하면 반복문 없이도 깔끔하고 선언적인 방식으로 두 배열 간의 id 매칭 결과를 처리할 수 있습니다.