티스토리 뷰

개발

[typescript] map 활용하기

복복2 2022. 9. 11. 17:21

typescript 의 map 활용

 

콜백 함수 (callback function)

파라미터로 함수를 전달받아서 함수의 내부에서 실행하는 함수

 

map

const array = [1, 2, 3, 5, 7];

const map = array.map(x => x * 2);

console.log(map);
// [2, 4, 6, 10, 14]

 

map 을 활용하기

type Product = {
  id: number;
  name: String;
  price: number;
};

const productList: Array<Product> = new Array<Product>();

productList.push({ id: 1, name: '신발', price: 10000 });
productList.push({ id: 2, name: '티셔츠', price: 30000 });
productList.push({ id: 3, name: '청바지', price: 50000 });
productList.push({ id: 4, name: '자켓', price: 90000 });

const sampleProduct: Product = { id: 5, name: '샘플', price: 10000 };
productList.push(sampleProduct);

객체의 특정 값만 추출

console.log(productList.map((list) => list.name));
// ["신발", "티셔츠", "청바지", "자켓", "샘플"]

객체의 특정 값을 변경하기

console.log(productList.map((list) => ({ ...list, price: list.price * 1.1 })));
/*
[
  { "id": 1, "name": "신발", "price": 11000 },
  { "id": 2, "name": "티셔츠", "price": 33000 },
  { "id": 3, "name": "청바지", "price": 55000 },
  { "id": 4, "name": "자켓", "price": 99000 },
  { "id": 5, "name": "샘플", "price": 11000 }
]
*/

특정 값을 추가하기

console.log(
  productList.map((list) => ({
    id: list.id,
    name: list.name,
    brand: 'nike',
    price: list.name == '청바지' ? list.price * 3 : list.price * 2,
  })),
);
/*
[
  { id: 1, name: '신발', brand: 'nike', price: 20000 },
  { id: 2, name: '티셔츠', brand: 'nike', price: 60000 },
  { id: 3, name: '청바지', brand: 'nike', price: 150000 },
  { id: 4, name: '자켓', brand: 'nike', price: 180000 },
  { id: 5, name: '샘플', brand: 'nike', price: 20000 }
]
*/
댓글