본문 바로가기

Front End/Javascript

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

Map -> String (Map to String)

JSON.stringify(Array.from( map.entries()));

        let map  = new Map();
        map.set(1,'한사람').set(2, '두사람').set(3,'세사람');
        let array = Array.from(map);
        let str = JSON.stringify(array);


String -> Map (String to Map)

new Map(JSON.parse(str));

 let map = new Map(JSON.parse(str));

 

 

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
<!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 map  = new Map();
        map.set(1,'한사람').set(2'두사람').set(3,'세사람');
 
        document.write(typeof(map) + " : " + map);
        document.write("<br>");
        let array = Array.from(map);
        document.write(typeof(array) + " : " + array);
        document.write("<br>");
        let str = JSON.stringify(array);
        document.write(typeof(str) + " : " + str);
        document.write("<br>");
        let json = JSON.parse(str);
        document.write(typeof(json) + " : " + json);
        document.write("<br>");
        document.write(json[0+ "<br>" + json[0][1+ "<br>");
        document.write(json[1+ "<br>" + json[1][1+ "<br>");
        document.write(json[2+ "<br>" + json[2][1+ "<br><hr/>");
 
        map = new Map(json);
        document.write(typeof(map) + " : " + map + "<br>");
        for(let e of map.entries()){
          document.write(e + "<br>");
        }
    </script>
</head>
 
<body>
 
</body>
 
</html>
cs

 

 

실행 결과 입니다.