LoginSignup
4
1

この記事は、Elixir Advent Calendar 2023 シリーズ10 の21日目です


【本コラムは、3分で読め、3分で試せます】

piacere です、ご覧いただいてありがとございます :bow:

マップリストは、同列の複数データを扱う際や、RepoによるDBデータ取得で頻出します

users = [
  %{id: :id000, name: "hoge", weight: 49}, 
  %{id: :id001, name: "foo",  weight: nil}, 
  %{id: :id002, name: "fuga", weight: 33}
]

下記コラムで更新について述べました

本コラムでは、削除を述べます

マップリストの全体から削除

users
|> Enum.map(& Map.drop(&1, [:name]))
[
+ %{id: :id000, weight: 49},
+ %{id: :id001, weight: nil},
+ %{id: :id002, weight: 33}
]

複数キー/バリューの一括削除もできます

users
|> Enum.map(& Map.drop(&1, [:id, :name]))
[
+ %{weight: 49}, 
+ %{weight: nil}, 
+ %{weight: 33}
]

全体に対してであれば、forでもシンプルに書けます

for u <- users, reduce: [] do
  acc -> acc ++ [Map.drop(u, [:name])]
end
[
+ %{id: :id000, weight: 49},
+ %{id: :id001, weight: nil},
+ %{id: :id002, weight: 33}
]

マップリストの一部のみ削除

users
|> Enum.map(& if &1.weight == nil, do: Map.drop(&1, [:weight]), else: &1)
[
  %{id: :id000, name: "hoge", weight: 49},
+ %{id: :id001, name: "foo"},
  %{id: :id002, name: "fuga", weight: 33}
]

case で書くなら、こうです

users
|> Enum.map(& case &1.weight do
    nil -> Map.drop(&1, [:weight])
    _ -> &1
  end)
[
  %{id: :id000, name: "hoge", weight: 49},
+ %{id: :id001, name: "foo"},
  %{id: :id002, name: "fuga", weight: 33}
]
4
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
4
1