배열이나 객체에서 특정 값을 제외한 나머지 데이터만 추출하고 싶다면, if 조건문 안에 논리 NOT(!) 연산자를 활용하면 됩니다. 조건이 거짓일 때(즉, 제외하려는 값이 아닐 때)만 원하는 코드가 실행되도록 만드는 방식입니다.
예제 코드
아래 예제에서는 고객 정보 배열에서 국가명이 "AUS"인 고객은 건너뛰고, 나머지 고객의 국가명만 콘솔에 출력합니다.
var customerDetails = [
{
customerName: "John",
customerAge: 28,
customerCountryName: "US"
},
{
customerName: "David",
customerAge: 25,
customerCountryName: "AUS"
},
{
customerName: "Mike",
customerAge: 32,
customerCountryName: "UK"
}
]
for (var i = 0; i < customerDetails.length; i++) {
if (customerDetails[i].customerCountryName != "AUS") {
console.log("The country name is=" + customerDetails[i].customerCountryName);
}
}위 프로그램을 실행하려면 터미널에서 다음 명령어를 입력하세요.
node fileName.js
여기서는 파일 이름을 demo179.js로 저장했다고 가정합니다.
실행 결과
프로그램을 실행하면 다음과 같은 출력 결과를 확인할 수 있습니다.
PS C:\Users\Amit\javascript-code> node demo179.js The country name is=US The country name is=UK
코드 설명
핵심은 !=(느슨한 같지 않음 연산자) 부분입니다. 반복문이 배열의 각 요소를 순회할 때, customerCountryName이 "AUS"와 같지 않은 경우에만 console.log()가 실행됩니다. 그 결과 David(AUS)의 정보는 자연스럽게 필터링되고, US와 UK 고객의 국가명만 출력됩니다.
참고로, 타입까지 엄격하게 비교하고 싶다면 !==(엄격한 비교 연산자)를 사용하는 것이 좋습니다. 이렇게 하면 의도치 않은 타입 변환으로 인한 버그를 예방할 수 있습니다.