본문 바로가기

Front End/Javascript

[JavaScript] 맵(Map) to Object, Object to Map

Object.entreis

object를 map으로 변환합니다.

let map = new Map(Object.entries(obj));


Object.fromEntries

map을 object로 변환합니다.

자료가 map에 저장되어있는데, third-party code에서 자료를 object로 넘겨받길 원할 때 이 방법을 사용할 수 있습니다.

let  obj = Object.fromEntries(map);

 

 

ex05.html 파일을 다음과 같이 만듭니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="ko">
 
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>javaScript Map</title>
    <script>
        let obj = {
            name"한사람",
            age: 34,
            gender : true,
            toString(){
                return `${this.name}(${this.age}세, ${this.gender ? '남자':'여자'})`; 
            }
        };
        document.write(`${JSON.stringify(obj)}<br>`);
        document.write(`${obj}<hr>`);     
        // 객체를 맵으로
        let map = new Map(Object.entries(obj));
        map.entries().forEach(([key, value])=>{
            // if(typeof(value)!='function')
            document.write(`${key} : ${value}<br>`);
        });
        document.write(`<hr>`); 
        
        // 맵을 
        obj = Object.fromEntries(map);
        document.write(`${JSON.stringify(obj)}<br>`);
        document.write(`${obj}<hr>`);     
        for(key in obj){
            // if(typeof(obj[key])!='function')
            document.write(`${key} : ${obj[key]}<br>`);
        }
        document.write(`<hr>`); 
        document.write(`${JSON.stringify(obj)}<hr>`); 
    </script>
</head>
 
<body>
 
</body>
 
</html>
cs

 

 

실행 결과 입니다.