【问题标题】:Get map by value from list in Elixir从 Elixir 的列表中按值获取地图
【发布时间】:2017-06-20 08:15:08
【问题描述】:

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

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

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

所以本质上:

dev_endpoint("foo@example.org")

应该返回:

%{email: "foo@example.org", account_type: "full"}

我知道我的捕获语法有问题,但我尝试了各种不同的迭代,但没有成功。

【问题讨论】:

  • 也许我不能完全理解你想要什么但endpoint |> Enum.find(&(email== Map.get(&1,:email)))不够吗?

标签: elixir phoenix-framework


【解决方案1】:

我认为您正在寻找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

现在你可以使用这个了:

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

【讨论】:

    猜你喜欢
    • 2011-05-10
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 1970-01-01
    • 2023-01-24
    • 2022-08-17
    • 2021-08-06
    • 2021-04-24
    相关资源
    最近更新 更多