TIL 35 | map

map을 쓰는데 이해가 잘 안되서 article을 보고 퍼온 내용이다.

출처: https://www.kpiteng.com/blogs/javascript-tips-tricks-best-practices/

Map - map()

Map is widely used by developers in daily coding, Map offers various use cases depending upon your custom requirement. Let's check in code,

var arrCity = [
  {
  'id': 1,
  'name': 'London',
  'region': 'UK',
  },
  {
  'id': 2,
  'name': 'Paris',
  'region': 'Europe',
  },
  {
  'id': 3,
  'name': 'New York',
  'region': 'United State',
  },
 ]

 
 const arrCityName = arrCity.map(city => city.name);
 console.log(arrCityName); // output: ['London', 'Paris', 'New York']
 

Many times we required to add new key-pari within existing array, Let's do that,

// Let's use arrCity over here,

arrCity.map(city => city.cityWithName = city.name + ' - ' + city.region);
console.log(arrCity); 

// output: 
[{
  cityWithName: "London - UK", // new key-pair 
  id: 1,
  name: "London",
  region: "UK"
}, {
  cityWithName: "Paris - Europe", // new key-pair 
  id: 2,
  name: "Paris",
  region: "Europe"
}, {
  cityWithName: "New York - United State", // new key-pair 
  id: 3,
  name: "New York",
  region: "United State"
}]

Let's use another approach and add new key-pair value,

// We will use same array - arrCity over here,

const newArrCity = arrCity.map((city) => ({
  ...city,
  newCity: true,
}));
console.log(newArrCity); 

// output: 
[{
  id: 1,
  name: "London",
  newCity: true, // new key-pair 
  region: "UK"
}, {
  id: 2,
  name: "Paris",
  newCity: true, // new key-pair 
  region: "Europe"
}, {
  id: 3,
  name: "New York",
  newCity: true, // new key-pair 
  region: "United State"
}]

Cast Values in array using - map()

Awesome tricks - harness the power of map function you will convert an array of strings into an array of numbers.


const arrStringValues = ['1', '2', '3', '4.567', '-89.95', [1.2345]];
const arrNumbers = arrStringValues.map(Number);

console.log(arrNumbers); // output: [1, 2, 3, 4.567, -89.95, 1.2345]

좋은 웹페이지 즐겨찾기