array to hashmap js

ex1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const arr = [
{ id: 1, value: 1 },
{ id: 2, value: 2 },
{ id: 3, value: 3 },
];

let map = new Map();

arr.reduce((newMap, cur) => {
const { id, value } = cur;
newMap.set(id, value);
return newMap;
}, map);

console.log(map);
map.get(1);
  • reduce로 합쳐주는 방식으로 할 수 있고
ex2
1
2
3
4
5
6
7
8
9
const arr = [
{ id: 1, value: 1 },
{ id: 2, value: 2 },
{ id: 3, value: 3 },
];

const map = new Map(arr.map((item) => [item.id, item.value]));

console.log(map);
  • array.map()과 Map 생성자로 짧고 이쁘게 변화해줄 수 있다

참고