dictionary - 如何检查 key 是否存在于 Elixir 的深度嵌套 Map 中

标签 dictionary elixir

我有一个 map 对象,我需要检查它是否包含给定的键。我试过如下,但它总是返回false。还有如何在 map 回复消息中提取值(value),

map=%{
  Envelope: %{
    Body: %{
      replyMessage: %{
        cc: %{
          "amount" => "100.00",
          "reasonCode" => "100",
        },
        decision: "ACCEPT",
        invalidField: nil,
        purchaseTotals: %{"currency" => "CAD"},
        reasonCode: "100",

      }
    }
  }
}
Map.has_key?(map,  %{Envelope: %{Body: %{replyMessage: replyMessage}}})= false

最佳答案

您有两种可能: Kernel.match?/2 检查 key 是否存在和/或 Kernel.get_in/2 深度找回值(value)。

iex|1 ▶ match?(%{Envelope: %{Body: %{replyMessage: _}}}, map)      
#⇒ true

iex|2 ▶ get_in(map, [:Envelope, :Body, :replyMessage])
#⇒ %{
#   cc: %{"amount" => "100.00", "reasonCode" => "100"},
#   decision: "ACCEPT",
#   invalidField: nil,
#   purchaseTotals: %{"currency" => "CAD"},
#   reasonCode: "100"
# }
小心 Kernel.get_in/2会返回 nil如果 key 存在,但具有 nil值,以及如果键不存在。

Map.has_key?/2 无论如何都不是递归的,它与 map 的键一起工作,作为参数传递;也就是说,只有第一级。

旁注:基于 Map.has_key/2,人们可能很容易自己构建一个递归解决方案。
defmodule Deep do
  @spec has_key?(map :: map(), keys :: [atom()]) :: boolean()
  def has_key?(map, _) when not is_map(map), do: false
  def has_key?(map, [key]), do: Map.has_key?(map, key)
  def has_key?(map, [key|tail]),
    do: Map.has_key?(map, key) and has_key?(map[key], tail)
end

Deep.has_key?(map, [:Envelope, :Body, :replyMessage])
#⇒ true

关于dictionary - 如何检查 key 是否存在于 Elixir 的深度嵌套 Map 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62844614/

相关文章:

hex - Elixir mix 自动确认

python - 构建一个将列表转换为字典并根据条件分配键值的函数

python - 如何从基于行的字典列表创建 Pandas DataFrame

c++ - 通过 C++ 套接字发送 std::map<int, std::map<std::string, double>> (linux)

elixir - 在不同的端口上运行 iex mix phoenix.server 不起作用

erlang - Erlang 系统中最大(实际)节点数是多少

elixir - 模式匹配映射作为函数参数

android - 在ListView中添加搜索: crashed when typing word

javascript - Topojson 比例问题

elixir - 如何在 Ecto 中进行子查询?