如何检查密钥是否存在于 Elixir 中的深层嵌套映射中

How to check if the key exists in a deeply nested Map in Elixir

我有一个地图对象,我需要检查它是否包含给定的键。我试过如下但它总是 return 错误。还有如何在内部地图 replyMessage 上提取值,

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 to check whether the key exists and/or Kernel.get_in/2深入检索值。

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 会 return nil 如果键存在,但有 nil 值,以及如果键不存在。


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


旁注:基于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