更新elixir地图

时间:2016-07-09 11:43:04

标签: elixir

拥有它:

[%{"id" => "1", "name" => "foo"},
 %{"id" => "2","name" => "bar"}]

如何将其转换为以下内容:

[%"foo" => %{"id" => "1","name" => "foo"},
 %"bar" => {"id" => "2","name" => "bar"}]

1 个答案:

答案 0 :(得分:2)

假设您需要Map String个密钥,可以for使用into:,如下所示:

iex(1)> entries = [%{"id" => "1", "name" => "foo"}, %{"id" => "2","name" => "bar"}]
[%{"id" => "1", "name" => "foo"}, %{"id" => "2", "name" => "bar"}]
iex(2)> for %{"name" => name} = entry <- entries, into: %{}, do: {name, entry}
%{"bar" => %{"id" => "2", "name" => "bar"},
  "foo" => %{"id" => "1", "name" => "foo"}}