JavaScript에서 특정 조건을 검사한 후 배열에 새 객체나 속성을 추가하려면 filter() 메서드와 map() 메서드를 함께 활용할 수 있습니다.
예제
const details =[
{ customerName: 'John', customerCountryName: 'UK', isMarried :true },
{ customerName: 'David', customerCountryName: 'AUS', isMarried :false },
{ customerName: 'Mike', customerCountryName: 'US', isMarried :false }
]
let tempObject = details.filter(obj=> obj.isMarried == true);
tempObject["customerNameWithIsMarriedFalse"] = details.filter(obj =>
obj.isMarried== false).map(obj => obj.customerName);
console.log(tempObject);
코드 설명
details 배열에는 고객의 이름, 국가, 결혼 여부(isMarried) 정보가 담겨 있습니다. 먼저 filter()를 사용해 isMarried 값이 true인 객체만 추출하여 tempObject에 저장합니다.
그다음, isMarried가 false인 객체들을 다시 filter()로 걸러낸 뒤 map()으로 고객 이름만 추출하여 새로운 속성 customerNameWithIsMarriedFalse에 배열 형태로 할당합니다.
위 프로그램을 실행하려면 다음 명령어를 사용합니다.
node fileName.js.
여기서는 파일 이름이 demo176.js라고 가정합니다.
출력 결과
이 코드를 실행하면 다음과 같은 결과가 출력됩니다.
PS C:\Users\Amit\javascript-code> node demo176.js
[
{ customerName: 'John', customerCountryName: 'UK', isMarried: true }, customerNameWithIsMarriedFalse: [ 'David', 'Mike' ]
]