LoginSignup
0
0

More than 1 year has passed since last update.

【Javascript】Mapオブジェクト(iteration)

Last updated at Posted at 2021-06-02

初めに

Mapオブジェクトについて学習した内容のoutput用記事です。

※内容に間違いなどがある場合はご指摘をよろしくお願いします。
※こちらの記事はあくまでも個人で学習した内容のoutputとしての記事になります。

前回の記事:
https://qiita.com/redrabbit1104/items/cc0d851da2a533cda694

Mapオブジェクトの生成

setメソッドを使わずにMapオブジェクトは以下のような方法で作れます。

  const bookStore = new Map([
        ["mon", { open: 10, close: 20 }],
        ["tue", { open: 11, close: 19 }],
        ["sun", { oepn: 0, close: 20 }],
      ]);

      console.log(bookStore);
//Map(3) {"mon" => {…}, "tue" => {…}, "sun" => {…}}

ObjectからMapオブジェクトへ

Mapの引数は配列の中に配列が入っている構造ですので、Objectのentriesメソッドで生成したものを丸ごとMapの引数にすればObjectからMapオブジェクトに簡単に変換することができます。

   const bookStore = {
        mon: { open: 10, close: 20 },
        tue: { open: 11, close: 19 },
        sun: { open: 0, close: 20 },
      };
      const entries = Object.entries(bookStore);
      console.log(entries);
      //(3) [Array(2), Array(2), Array(2)]

      const newMap = new Map(entries);
      console.log(newMap);
      //Map(3) {"mon" => {…}, "tue" => {…}, "sun" => {…}}

for of文を使ったloop

また、for ofを使ってkeyの値に該当するvalueだけをコンソールに表示することもできます。

 const items = new Map([
        ["name", "John"],
        [1, "school"],
        [2, "home"],
        [true, "Yes"],
        [false, "No"],
      ]);

      for (const [key, value] of items) {
        if (typeof key === "number") 
        console.log(`Guess ${key}: ${value}`);
      }]
      //Guess 1: school
      // Guess 2: home

typeofでキーの値が数字だけの場合に値を出力することができました。

Mapオブジェクトを配列にする

Spread構文を使えば、Mapオブジェクトを配列にすることもできます。

         console.log([...items]);
      //(6) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]

      console.log([...items.entries()]);
      //(6) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2)]

      console.log([...items.keys()]);
      //(6) ["name", 1, 2, "正解", true, false]

      console.log([...items.values()]);
      //(6) ["John", "school", "home", 2, "Yes", "No"]

参考サイト

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