2
1

More than 3 years have passed since last update.

JavaScriptのMapオブジェクトでmap関数やfilter関数を使いたい

Posted at

概要

ES6からJavaScriptではMapオブジェクトと呼ばれる、キーと値の組み合わせを保持することができるオブジェクトが使用できます。詳しい仕様については、@chihiroさんのJavaScript Mapオブジェクトにまとめられています。
この、Mapオブジェクトについて反復処理を行いたい場合は、forEachやfor文で値を取り出していくのですが、ではmap関数やfilter関数を使いたい場合どうすれば良いのかというのを今回記事にまとめました。

対応

Convert ES6 Iterable to Arrayの記事にある通り、Array.from()関数ではMapオブジェクトやIterableオブジェクトを配列に変換できます。ので対象のオブジェクトを一度配列に変換した後に、map関数やfilter関数を使用するのが対応の一つとして考えられます。

実装サンプル

【Mapオブジェクトでmap関数を使用】

MapオブジェクトをArray.from()にかけた場合は、keyとvalueがセットになった配列をmap関数内で取得できます。実装サンプルは以下です。

sampleMap.js
const sampleMap = new Map([["key1", 1000], ["key2", 1001], ["key3", 1003]]);
const sampleMap2 = Array.from(sampleMap).map((s) => {
  return {
    afterMapKey: s[0],
    afterMapValue: s[1],
  };
});

<結果>

[
  {afterMapKey: "key1", afterMapValue: 1000},
  {afterMapKey: "key2", afterMapValue: 1001},
  {afterMapKey: "key3", afterMapValue: 1003}
]

【Mapオブジェクトのkeys()でmap関数を使用】

Mapオブジェクトのkeys()の結果をArray.from()にかけた場合は、単純にkeyの文字列の配列がmap関数内で取得できます。

sampleMapKeys.js
const sampleMap = new Map([["key1", 1000], ["key2", 1001], ["key3", 1003]]);
const sampleMapKeys = Array.from(sampleMap.keys()).map((s) => {
  return {
    afterMapKey: s,
  };
});

<結果>

[
  {afterMapKey: "key1"},
  {afterMapKey: "key2"},
  {afterMapKey: "key3"}
]
2
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
2
1