0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypescriptでMap⇄JSONを実装する

Posted at

端書き

結論

// Mapオブジェクトを作成する
let map = new Map()
let hoge = {
  setting: {
    label: 'aaa'
  },
  value: 'bbb',
  isError: false,
}
let huga = {
  setting: {
    label: 'ccc'
  },
  value: 'ddd',
  isError: true,
}
map.set('huga', huga)
map.set('hoge', hoge)
map.forEach((value,key) => {
  console.log('key: ' + key + ' value:' + JSON.stringify(value))
})
// > "key: hoge value:{"setting":{"label":"aaa"},"value":"bbb","isError":false}"
// > "key: huga value:{"setting":{"label":"ccc"},"value":"ddd","isError":true}"

// JSON化する
let toJson = JSON.stringify(Array.from(map.entries()));
console.log('toJson: ' + toJson)
// > "toJson: [["hoge",{"setting":{"label":"aaa"},"value":"bbb","isError":false}],["huga",{"setting":{"label":"ccc"},"value":"ddd","isError":true}]]"

// 再度MAPオブジェクト化する
let toMap = new Map(JSON.parse(toJson));
toMap.forEach((value,key) => {
  console.log('key: ' + key + ' value:' + JSON.stringify(value))
})
// > "key: hoge value:{"setting":{"label":"aaa"},"value":"bbb","isError":false}"
// > "key: huga value:{"setting":{"label":"ccc"},"value":"ddd","isError":true}"

戻った!

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?