lapinkoira
lapinkoira

Reputation: 8978

Convert list with one item (map) to map

How would you convert [%{"hello" => 123}] to just %{"hello" => 123}?

I could Enum.at(map, 0) but doesnt look good.

Upvotes: 1

Views: 100

Answers (2)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

While the answer by @guitarman is perfectly correct, there is also Kernel.hd/1 than takes the head of the list:

iex> [%{"hello" => 123}] |> hd()
%{"hello" => 123}

The difference is pattern matching to the one-element-list ([map] =) would raise MatchError on an empty list (the above raises ArgumentError,) and the latter will successfully return a value when the list has more than one element.

Upvotes: 3

guitarman
guitarman

Reputation: 3310

You could use pattern matching:

iex(1)> [map] = [%{"hello" => 123}]
iex(2)> map
# => %{"hello" => 123}

or

iex(1)> [%{"hello" => value} = map] = [%{"hello" => 123}]
iex(2)> map
# => %{"hello" => 123}
iex(3)> value
# => 123

if you need the value for the "hello" key.

Upvotes: 4

Related Questions