1
0

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 1 year has passed since last update.

jsのmapのentryをイテレーション的な感じで処理したい

Posted at

map内の要素をフィルタしたいときがあって調べました。

解決法

Array.from()でarrayを生成すると、mapの各要素(entryと呼ぶ)が以下のようにマッピングされるのでそれを利用する。

  • key -> entry[0]
  • value -> entry[1]

サンプルコード

const sampleMap = new Map();
sampleMap.set("id1", { name: "name1", hoge: "hoge1" });
sampleMap.set("id2", { name: "name2", hoge: "hoge2" });
sampleMap.set("id3", { name: "name3", hoge: "hoge3" });

const filteredList = Array.from(sampleMap)
  .filter((entry) => entry[1].name !== "name1")
  .map((entry) => ({
    id: entry[0],
    name: entry[1].name,
    hoge: entry[1].hoge
  }));

filteredList.forEach((e) => {
  console.log(e.id +' '+ e.name+' '+e.hoge);
});
// id2 name2 hoge2 
// id3 name3 hoge3
1
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?