简体   繁体   English

Elixir将struct转换为map

[英]Elixir convert struct to map

I'm trying to convert a struct to a map to be able to clean all the nil values 我正在尝试将结构转换为地图,以便能够清除所有的nil值

I'm currently using this code 我目前正在使用此代码

  case Nadia.get_updates  do
    {:ok, results} ->
      Map.from_struct(results)
      |> Enum.filter(fn {_, v} -> v != nil end)
      |> Enum.into(%{})

Note: Nadia.get_updates returns the following structure: https://hexdocs.pm/nadia/Nadia.Model.Update.html#t:t/0 注意:Nadia.get_updates返回以下结构: https ://hexdocs.pm/nadia/Nadia.Model.Update.html#t:t / 0

Yet I'm always receiving the following error: no function clause matching in Map.from_struct/1 然而,我总是收到以下错误:Map.from_struct / 1中没有匹配的函数子句

Since v0.15 we have Map.from_struct/1 which does exactly this. v0.15开始,我们有Map.from_struct/1 ,它就是这样做的。

defmodule User do
  defstruct [:name]
end

Map.from_struct(%User{name: "valim"})
#=> %{name: "valim"}

There's another trick 还有另一招

my_struct = %MyStruct{}
my_map = Map.delete my_struct, :__struct__
get_updates([{atom, any}]) ::
  {:ok, [Nadia.Model.Update.t]} |
  {:error, Nadia.Model.Error.t}

If successful it returns a list of Nadia.Model.Update.t. 如果成功,则返回Nadia.Model.Update.t列表。 That's why you get that error. 这就是你得到那个错误的原因。

FWIW, I wrote a library that will do this kind of thing for you automagically w/o having to pull the data structure apart. FWIW,我写了一个库,可以自动为你做这种事情,而不必将数据结构分开。

https://github.com/philosophers-stone/transform https://github.com/philosophers-stone/transform

This is from the test code: 这是来自测试代码:

test "implement scrub of empty values from map" do
  data = %{ :a => nil, :b => "", :c => "a"}
  replace_empty = fn(string, _d) -> if( string == "", do: nil , else: string) end
  replace_nil = fn(map, _depth) ->  for {k, v} <- map, v != nil , into: %{}, do: {k, v} end
  potion = %{ BitString => replace_empty, Map => replace_nil}

  assert PhStTransform.transform(data, potion) == %{:c => "a"}

end

Note, if data was a list of maps this would still work just fine. 请注意,如果数据是地图列表,这仍然可以正常工作。 The PhStTransform library will just keep pulling the data apart until it finds a map. PhStTransform库将继续将数据拉开,直到找到一张地图。 In your case you would use a replace_nil function that worked on the kinds of structs you are interested in. 在您的情况下,您将使用replace_nil函数,该函数处理您感兴趣的结构类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM