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]
Author And Source
이 문제에 관하여(TIL 35 | map), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://velog.io/@moonsirl9123/TIL-35-map저자 귀속: 원작자 정보가 원작자 URL에 포함되어 있으며 저작권은 원작자 소유입니다.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)