[TIL] JavaScript - Map 메서드

Simple Key·2020년 5월 6일
0

map

map()배열의 내의 각각의 요소마다 주어진 함수를 호출해서 적용된 결과를 새 배열로 리턴한다.

const array1 = [1, 2, 3, 4, 5, 6];
const map1 = array1.map(x => x * 10);

console.log(map1);
// 결과는 [10, 20, 30, 40, 50, 60]

문법

arr.map(callback(currentValue, index ,array) , thisArg)

map의 매개변수로는 callbackthisArg 두개가 있다.
callback내에는 다시 currentValue, 'index', 'array' 3개의 매개변수를 갖는다.

  • currentValue : 배열 내 현재 값
  • index : 배열 내 현재 값의 인덱스
  • array : 현재 배열

예시

let test = () => {
  let testArr = [1, 2, 3, 4, 5];
  let returnArr = testArr.map((currentValue, index, array)=>{
    console.log(currentValue);
    console.log(index);
    console.log(array);
    return currentValue*2
  })
}
console.log(test());

기존 testArr 배열의 값에 곱하기 2가 되어진 새로운 returnArr가 만들어졌다.


map 함수는 객체도 제어가 가능하다.

let test = () => {
  let testData = [
    {'이름':'이수근', '계급':'병장'},
    {'이름':'민경훈', '계급':'상병'},
    {'이름':'강호동', '계급':'일병'},
    {'이름':'마동석', '계급':'이등병'}
  ];
  let newData = testData.map((data)=>{
    let returnData = {};
    returnData[data['이름']] = data['계급']
    return returnData
  })
  console.log(newData);
}
test();

기존 testData 객체에서 '이름'과 '계급'을 빼고 값으로만 새 객체 newData를 만드는 코드

profile
프론트엔드 개발자 심기현 입니다.

0개의 댓글