Elixir:在此Map中将索引从字符串转换为整数

时间:2018-06-22 02:25:21

标签: string dictionary int elixir

有人可以帮我找出一种干净的方法,将从前端输入的索引作为字符串转换为整数吗?下面是有问题的地图。

%{
  "0" => %{
    "daysOfWeek" => [], 
    "start" => nil, 
    "stop" => nil
  }, 
  "1" => %{
    "daysOfWeek" => [], 
    "start" => nil, 
    "stop" => nil
  }, 
  "2" => %{
    "daysOfWeek" => [], 
    "start" => nil, 
    "stop" => nil
  }
}

1 个答案:

答案 0 :(得分:2)

我将使用for,将密钥通过String.to_integer/1,然后收集到一个空的地图中:

iex(2)> map
%{
  "0" => %{"daysOfWeek" => [], "start" => nil, "stop" => nil},
  "1" => %{"daysOfWeek" => [], "start" => nil, "stop" => nil},
  "2" => %{"daysOfWeek" => [], "start" => nil, "stop" => nil}
}
iex(3)> for {k, v} <- map, into: %{}, do: {String.to_integer(k), v}
%{
  0 => %{"daysOfWeek" => [], "start" => nil, "stop" => nil},
  1 => %{"daysOfWeek" => [], "start" => nil, "stop" => nil},
  2 => %{"daysOfWeek" => [], "start" => nil, "stop" => nil}
}