JavaScript에서 중첩된 JSON 배열 구조 안에 있는 특정 키의 값만 깔끔하게 추출하고 싶다면, 배열 메서드인 map()을 활용하는 것이 가장 간단하고 효율적인 방법입니다.
JSON 배열 예시
먼저 다음과 같은 JSON 배열이 있다고 가정해 보겠습니다. 각 객체는 customerDetails라는 배열을 포함하고 있으며, 그 안에 고객 이름과 국가 정보가 들어 있습니다.
var details = [
{
"customerDetails": [
{
"customerName": "John Smith",
"customerCountryName": "US"
}
]
},
{
"customerDetails": [
{
"customerName": "David Miller",
"customerCountryName": "AUS"
}
]
},
{
"customerDetails": [
{
"customerName": "Bob Taylor",
"customerCountryName": "UK"
}
]
}
]map()으로 customerName 값만 추출하기
map() 메서드는 배열의 각 요소를 순회하면서 콜백 함수의 반환 값으로 새로운 배열을 만들어 줍니다. 따라서 각 객체에서 customerDetails[0].customerName에 접근하면 고객 이름만 담긴 새로운 배열을 손쉽게 얻을 수 있습니다.
var details = [
{
"customerDetails": [
{
"customerName": "John Smith",
"customerCountryName": "US"
}
]
},
{
"customerDetails": [
{
"customerName": "David Miller",
"customerCountryName": "AUS"
}
]
},
{
"customerDetails": [
{
"customerName": "Bob Taylor",
"customerCountryName": "UK"
}
]
}
]
var allCustomerName = details.map(obj =>
obj.customerDetails[0].customerName);
console.log(allCustomerName);프로그램 실행 방법
위 프로그램을 실행하려면 Node.js 환경에서 다음 명령어를 사용합니다. 여기서는 파일 이름이 demo206.js라고 가정합니다.
node fileName.js
출력 결과
명령어를 실행하면 콘솔에 다음과 같이 고객 이름만 담긴 배열이 출력됩니다.
PS C:\Users\Amit\javascript-code> node demo206.js [ 'John Smith', 'David Miller', 'Bob Taylor' ]
핵심 정리
중첩된 JSON 구조에서 특정 필드 값을 추출할 때는 map()을 사용하면 반복문 없이 한 줄의 코드로 처리할 수 있습니다. details.map(obj => obj.customerDetails[0].customerName)처럼 접근 경로를 콜백 함수에 명시하기만 하면, 원하는 값들로 이루어진 새로운 배열을 즉시 반환받을 수 있습니다. 코드가 간결해질 뿐만 아니라 가독성도 크게 향상되므로, 실무에서 데이터 변환 작업 시 적극적으로 활용해 보시기 바랍니다.