배워서 남 주자

배열 map 메소드 활용법

미래에서 온 개발자 2022. 12. 29. 23:02

기존 배열은 건드리지 않은 채 배열의 어떤 값을 변경해서 새로운 배열로 반환하고 싶을 때 map 메소드를 자주 쓴다. React, Redux 등 데이터의 불변성(immutability)이 중요한 라이브러리에서 데이터를 다룰 때 자주 쓰는 메소드 중 하나이다. 

 

다음과 같은 user 정보가 담긴 객체가 들어 있는 배열을 예로 들어보자. 

 

const users = [
  {
    id: 1,
    name: "이정도",
    username: "jd1386",
    email: "lee.jungdo@gmail.com",
    phone: "010-3192-2910",
    website: "https://leejungdo.com",
    province: "경기도",
    city: "성남시",
    createdAt: "2019-02-24T16:17:47.000Z",
    updatedAt: "2019-02-24T16:17:47.000Z",
  },
  {
    id: 2,
    name: "김재완",
    username: "lastrites2018",
    email: "jaewan@gmail.com",
    phone: "02-879-5000",
    website: "https://github.com/lastrites2018",
    province: "",
    city: "서울특별시",
    createdAt: "2019-02-24T16:17:47.000Z",
    updatedAt: "2019-02-24T16:17:47.000Z",
  },
  {
    id: 3,
    name: "김성은",
    username: "sunnysid3up",
    email: "sunny@daum.net",
    phone: "010-4280-1991",
    website: "https://github.com/sunnysid3up",
    province: "경상남도",
    city: "창원시",
    createdAt: "2019-02-24T16:17:47.000Z",
    updatedAt: "2019-02-24T16:17:47.000Z",
  },
  {
    id: 4,
    name: "이주연",
    username: "yyijoo",
    email: "jooyeon@gmail.com",
    phone: "010-2940-1401",
    website: "https://github.com/yyijoo",
    province: "경기도",
    city: "용인시",
    createdAt: "2019-02-24T16:17:47.000Z",
    updatedAt: "2019-02-24T16:17:47.000Z",
  },
  {
    id: 5,
    name: "구일모",
    username: "johnnykoo84",
    email: "johnny@gmail.com",
    phone: "010-8491-3982",
    website: "https://github.com/johnnykoo84",
    province: "",
    city: "서울특별시",
    createdAt: "2019-02-24T16:17:47.000Z",
    updatedAt: "2019-02-24T16:17:47.000Z",
  },
];

 

1. 새로운 형태의 값 생성

배열에 들어있는 값 중 특정 값만 추출해서 새로운 형태의 배열로 반환할 수 있다. 예를 들어 사용자의 이름만 빼와서 새로운 배열을 만들 수 있다. users는 요소가 객체인 배열이었지만 userName은 사용자의 이름을 string 값으로 갖는 배열이다. 

 

const userName = users.map((el) => el.name);
console.log(userName); // [ '이정도', '김재완', '김성은', '이주연', '구일모' ]

 

2. 특정 요소만 재정의

배열에 들어있는 요소 중 특정 조건을 만족하는 대상만 값을 재정의해서 사용할 수 있다. 가령 경상남도 창원시가 창원특례시로 바뀌어서 해당 정보를 수정해야 할 필요가 있다고 할 때, city 값이 창원시인 요소를 찾아서 창원특례시로 바꾼 배열을 새로 만들 수 있다. 

 

map은 메소드 이름대로 1:1 매칭을 하는 메소드이기 때문에 특정 조건을 만족하지 않는 경우, 즉 else문에 기존 요소를 return해 주지 않으면 전부 undefined가 반환되는 점에 주의해야 한다. 

 

const newUsersInfo = users.map((el) => {
  if (el.city === "창원시") {
    return { ...el, city: "창원특례시" };
  } else return el;
});

// 삼항연산자로 코드를 더 간결하게 적을 수도 있다.
const newUsersInfo = users.map((el) => el.city === "창원시" ? { ...el, city: "창원특례시" } : el);

2번째 요소의 city 값이 "창원특례시"로 변경된 배열이 생성되었다

 

데이터 출처: Korean Json