从Elixir的列表中获取值的地图

gos*_*eti 1 elixir phoenix-framework

我正在创建一个简单的服务,它接收一个电子邮件地址 - 并从用户列表中找到用户.

这是一个包含用户列表的简化版本.我想根据用户的电子邮件地址提取用户.

def endpoint do
  [%{email: "foo@example.org", account_type: "full"}, 
   %{email: "bar@earxample.org", account_type: "standard"}, 
   %{email: "baz@example.org", account_type: "full"}]
end

def get_by_email(user, email) do
  user |> Map.get(:email)
end

def dev_endpoint(email) do
  endpoint
  |> Enum.map(&get_by_email(email)/1)
end

def show(conn, %{"id" => email}) do
  response = dev_endpoint(email)
  json(conn, %{"email" => response}) 
end
Run Code Online (Sandbox Code Playgroud)

基本上:

dev_endpoint("foo@example.org")
Run Code Online (Sandbox Code Playgroud)

应该返回:

%{email: "foo@example.org", account_type: "full"}
Run Code Online (Sandbox Code Playgroud)

我知道我的捕获语法有问题,但我尝试了各种不同的迭代,没有运气.

She*_*yar 5

我想你在找Enum.find/2.我就是这样用的:

def endpoint do
  [%{email: "foo@example.org",   account_type: "full"}, 
   %{email: "bar@earxample.org", account_type: "standard"}, 
   %{email: "baz@example.org",   account_type: "full"}]
end

def find_by_email(email) do
  Enum.find(endpoint, fn u -> u.email == email end)
end
Run Code Online (Sandbox Code Playgroud)

现在你可以使用这个:

iex> MyModule.find_by_email("foo@example.org")
%{email: "foo@example.org", account_type: "full"}
Run Code Online (Sandbox Code Playgroud)