프론트엔드/JavaScript

(JavaScript) 7. map() 기본 사용법

그린티_ 2025. 5. 2. 11:55
반응형

진짜 이거 처음에 쓸 때는 너무 어떻게 슬지 매번 찾아보고 썼는데.. 확실히 손에 익히면 금방 편안해짐!

map()은 배열의 각 요소를 변환하여 새로운 배열을 반환하는 함수

for문 대신 사용 가능하지만, 기존 배열을 변경하지 않고 새로운 배열을 생성함!

const numbers = [1, 2, 3, 4, 5];

const squared = numbers.map(num => num * num);

console.log(squared); // [1, 4, 9, 16, 25]

 

1. for문과 map() 비교

for문을 사용한 경우:

const arr = [1, 2, 3, 4, 5];
const newArr = [];

for (let i = 0; i < arr.length; i++) {
    newArr.push(arr[i] * 2);
}

console.log(newArr); // [2, 4, 6, 8, 10]

map()을 사용하면 이렇게 더 간결해진 답니당!

const newArr = arr.map(num => num * 2);
console.log(newArr); // [2, 4, 6, 8, 10]

2. 객체 배열에서 map() 사용

map()은 배열이 객체로 이루어져 있을 때 특정 속성만 가져올 수도 있음

const users = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 },
    { name: "Charlie", age: 35 }
];

const names = users.map(user => user.name);
console.log(names); // ["Alice", "Bob", "Charlie"]

 

3. map()을 활용한 문자열 변환

배열의 모든 문자열을 대문자로 변환하는 예제:

const words = ["hello", "world", "javascript"];
const upperCaseWords = words.map(word => word.toUpperCase());

console.log(upperCaseWords); // ["HELLO", "WORLD", "JAVASCRIPT"]

4. map()과 템플릿 문자열 사용

배열을 map()으로 변환하여 특정 형식의 문자열로 만들 수도 있음

const fruits = ["사과", "바나나", "오렌지"];
const fruitList = fruits.map(fruit => `과일: ${fruit}`);

console.log(fruitList);
// ["과일: 사과", "과일: 바나나", "과일: 오렌지"]

5. map()을 사용한 JSX (React에서 사용 예시)

React에서 map()은 리스트를 렌더링할 때 자주 사용됨!

const fruits = ["사과", "바나나", "오렌지"];

const fruitList = fruits.map((fruit, index) => <li key={index}>{fruit}</li>);

console.log(fruitList);
// <li key=0>사과</li>
// <li key=1>바나나</li>
// <li key=2>오렌지</li>

6. map()으로 객체 배열을 HTML 리스트로 변환

const users = [
    { id: 1, name: "Alice" },
    { id: 2, name: "Bob" },
    { id: 3, name: "Charlie" }
];

const userList = users.map(user => `<li>${user.name}</li>`);

console.log(userList.join(""));
// <li>Alice</li><li>Bob</li><li>Charlie</li>

 

정리

  • map()은 기존 배열을 변경하지 않고 새로운 배열을 생성함
  • 배열의 각 요소를 변환하여 사용하기 쉽고, for문보다 간결함!
  • React JSX에서 리스트를 렌더링할 때도 유용함!
    • 6번 블로그에서도 말했지만 서버에서 데이터 많이 받아올 때도 map을 주로 사용했었음 ㅎㅎ
반응형