Contents
see ListJavaScript jQuery map() 배열 변환 가이드
jQuery map() 메서드로 폼 요소 값을 배열로 변환하는 방법입니다. 체크박스, 입력 필드 등 여러 값을 효율적으로 수집합니다.
1. 기본 사용법
// 기본 문법
var result = $(selector).map(function(index, element) {
return 값;
}).get(); // .get()으로 순수 배열 변환2. 체크된 체크박스 값 수집
<input type="checkbox" name="items" value="1" checked>
<input type="checkbox" name="items" value="2">
<input type="checkbox" name="items" value="3" checked>
// 체크된 값만 배열로
var checkedValues = $("input[name=items]:checked").map(function() {
return $(this).val();
}).get();
// 결과: ["1", "3"]
// 숫자로 변환
var checkedIds = $("input[name=items]:checked").map(function() {
return parseInt($(this).val(), 10);
}).get();
// 결과: [1, 3]3. 텍스트 입력값 수집
<input type="text" class="item-qty" value="10">
<input type="text" class="item-qty" value="20">
<input type="text" class="item-qty" value="30">
var quantities = $(".item-qty").map(function() {
return $(this).val();
}).get();
// 결과: ["10", "20", "30"]4. 객체 배열 생성
<tr class="product-row" data-id="101">
<td class="name">상품A</td>
<td class="price">1000</td>
<td><input class="qty" value="2"></td>
</tr>
var products = $(".product-row").map(function() {
return {
id: $(this).data("id"),
name: $(this).find(".name").text(),
price: parseInt($(this).find(".price").text()),
qty: parseInt($(this).find(".qty").val())
};
}).get();
// 결과: [{id: 101, name: "상품A", price: 1000, qty: 2}, ...]5. 선택 옵션 값
<select id="categories" multiple>
<option value="1" selected>전자</option>
<option value="2">의류</option>
<option value="3" selected>식품</option>
</select>
var selected = $("#categories option:selected").map(function() {
return $(this).val();
}).get();
// 결과: ["1", "3"]6. 테이블 데이터 추출
// 특정 열의 모든 값
var names = $("table tbody tr td:nth-child(2)").map(function() {
return $(this).text().trim();
}).get();
// 전체 테이블 데이터
var tableData = $("table tbody tr").map(function() {
var row = $(this).find("td").map(function() {
return $(this).text().trim();
}).get();
return [row];
}).get();7. 조건부 필터링
// 빈 값 제외
var values = $(".input-field").map(function() {
var val = $(this).val().trim();
return val.length > 0 ? val : null;
}).get();
// 특정 조건만
var validPrices = $(".price").map(function() {
var price = parseInt($(this).text());
return price > 0 ? price : null;
}).get();8. 서버 전송용 데이터
// JSON으로 전송
var items = $(".cart-item").map(function() {
return {
productId: $(this).data("product-id"),
quantity: $(this).find(".qty").val()
};
}).get();
$.ajax({
url: "/api/cart",
type: "POST",
contentType: "application/json",
data: JSON.stringify({ items: items })
});map() vs each() 비교
| 메서드 | 용도 | 반환값 |
|---|---|---|
| map() | 값 변환/수집 | 새 배열 |
| each() | 순회/처리 | 없음 |
주의사항
- .get() 호출해야 순수 JavaScript 배열
- null/undefined 반환 시 결과에서 제외
- this는 DOM 요소, $(this)로 jQuery 객체 변환