LoginSignup
1
0

More than 1 year has passed since last update.

Mapオブジェクトはmapメソッドを使用できる【Javascript,Typescript】

Posted at

概要

Mapオブジェクトを反復で使おうとする際、何も考えず下記のように書くとプロパティ 'map' は型 'Map<string>' に存在しません。と注意される。

const hoge = new Map();
hoge.set("key1","value1");
hoge.set("key2","value2");
hoge.map(x=>console.log(x))//Error: hoge.map is not a function

これは単純な理由で、Mapにはmapが実装されていないためだ。

しかし、上記の代わりに下記を書くと問題なく実行できる。

const hoge = new Map();
hoge.set("key1","value1");
hoge.set("key2","value2");
[...hoge].map(x=>console.log(x))
//> Array ["key1", "value1"]
//> Array ["key2", "value2"]

これはMapが 反復可能プロトコル に沿っているからだ。

String, Array, TypedArray, Map, Set は、すべての組み込み反復可能オブジェクトです。

この反復オブジェクトは[...hoge]のような、スプレッド構文を使用することで展開ができる。

const hoge = new Map();
hoge.set("key1","value1");
hoge.set("key2","value2");
console.log([...hoge])// Array [Array ["key1", "value1"], Array ["key2", "value2"]]

よって、Mapオブジェクトでも以下のようにmapメソッドを用いることができる。

const hoge = new Map();
hoge.set("key1","value1");
[...hoge].map(x=>console.log(x))

これはどこで使うの?

ReactでMapメソッドを用いて重複をチェックしつつ配列管理を行いたい際に、Mapをそのままコンポーネントに落とし込めるのではないか?と考えている。近日中に記事を書いてここに追記する。

まとめ

Mapは反復可能プロトコルに沿っているため、スプレッド構文を用いることで[[key1,value1],[key2,value2]]という配列に展開でき、展開されたものはArrayのためmapメソッドが使用できる。

1
0
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
1
0