简体   繁体   中英

Trasform list in tuple in Elixir

I have a list like this

[%{User: "1"}, %{User: "2"}]

After use

HTTPoison.request(method, url, body, headers, option)

Where headers is

\"headers\":[{\"User\":\"1\"},{\"User_2\":\"2\"}]\r\n}

I'd like to have a structure like this

[{:user, "1"},{:user, "2"},{"content-type", "application/json"}]

And add even

{"content-type", "application/json"}

But I don't understand how can I trasform my data(user) in tuple

It is not very clear what exactly you want to transform and how.

Suppose you are want to transform [%{User: "1"}, %{User: "2"}] into [{user: "1"},{user: "2"}] .

[%{User: "1"}, %{User: "2"}]
|> Enum.map(fn(item) -> {:user, item[:User]} end)

Will produce

[user: "1", user: "2"]

And the result is equal to [{:user, "1"},{:user, "2"}] (keyword list).

Using the Kernel.SpecialForms.for/1 comprehension:

for %{User: id} <- [%{User: "1"}, %{User: "2"}], do: {:user, id}
#⇒ [user: "1", user: "2"]

Please note, that [user: "1", user: "2"] and [{:user, "1"}, {:user, "2"}] are exactly equivalent . That said, both represent the same list of tuples (of size 2.)

To add a new tuple: just add it to the list:

[
  {"content-type", "application/json"} |
  (for %{User: id} <- [%{User: "1"}, %{User: "2"}], do: {:user, id})
]
#⇒ [{"content-type", "application/json"},
#   {:user, "1"},
#   {:user, "2"}]

or, to the end (expect performance hits when appending elements to the end of a list, it's always better to prepend as shown above and List.reverse/1 afterwards):

users = for %{User: id} <- [%{User: "1"}, %{User: "2"}],
        do: {:user, id}
users ++ [{"content-type", "application/json"}]

To convert maps to respective keyword lists (tuples of size 2), use Enum.flat_map/2 :

[%{foo: "1"}, %{baz: "2"}, %{bix: "3"}]
|> Enum.flat_map(&Map.to_list/1)
#⇒ [foo: "1", baz: "2", bix: "3"]

To get keys as strings:

[%{foo: "1"}, %{baz: "2"}, %{bix: "3"}]
|> Enum.flat_map(fn map ->
     for {k, v} <- map, do: {Atom.to_string(k), v}
   end)
#⇒ [{"foo", "1"}, {"baz", "2"}, {"bix", "3"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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