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

JavaScript mapメソッドではまった話(React)

1
Last updated at Posted at 2026-06-22

前回の投稿

本題

今ポートフォリオとして作成しているディズニーリゾートのアトラクションを自分で 一覧化、お気に入り、感想などを登録できるアプリの中で
アトラクションがどのエリアにあるどうか選択するセレクトボックスを
Reactでvalueが配列のオブジェクトを
mapメソッドを用いて
<select>
  <optgroup label={obj key}>
    <option>{obj value}</option>
  </optgroup>
</select>

の形にしたかったのですがなかなかに嵌ってしまったので備忘録として残します。
複雑すぎて絶対に他の方法あると思いますが自分が思いつく限りの方法でやりました。
他にいい方法があればご教示ください。

使用する大元の配列

const areas = {
    "Tokyo Disney Land": [
        "World Bazaar",
        "Adventureland",
        "Westernland",
        "Critter Country",
        "Fantasyland",
        "Toontown",
        "Tomorrowland",
    ],
    "Tokyo Disney Sea": [
        "Mediterranean Harbor",
        "American Waterfront",
        "Port Discovery",
        "Lost River Delta",
        "Fantasy Springs",
        "Arabian Coast",
        "Mermaid Lagoon",
        "Mysterious Island",
    ],
};

解決法

1

まずオブジェクトをObject.entries()使用してオブジェクトのkeyとvalueを配列の形に変換する ([配列],[配列]]
const arr = Object.entries(areas) // 出力結果  [Array(2), Array(2)] 

2

変換してできた配列をmapでオブジェクトに変換する([{obj},{obj}])

 const areasArray = arr.map((key) => ({[key[0]]:key[1}) //出力結果 [{…}, {…}]

3

セレクトボックス内でループさせる
*mapのkeyは省略しています

<select>
    {areasArray.map((park) => (
      <>
        <optgroup label={Object.keys(park)}></optgroup> // objのkeyをlabelに付ける        
        {areas[Object.keys(park)].map((area) =>  // 元の配列からObject.keysでkeyを指定してmapでループさせる 
        (<option>{area}</option>))}
         
      </>
    ))}
</select>

改めて見ても複雑ですが自分にはこれが限界でした。
まだまだ勉強不足だなと感じます。

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