Kirkland
Kirkland

Reputation: 2533

How to concatenate lists from map properties in Elixir?

I have...

%{
  "errors" => %{
    "abc" => ["example", "something"],
    "xyz" => ["thing goes here"]
  }
}

I want...

["example", "something", "thing goes here"]

What's the cleanest way to get there?

Upvotes: 0

Views: 102

Answers (1)

Brett Beatty
Brett Beatty

Reputation: 5993

If you don't need an order guarantee on which error keys come first, you could combine Map.values/1 with List.flatten/1 or use a comprehension to do it pretty easily

map = %{
  "errors" => %{
    "abc" => ["example", "something"],
    "xyz" => ["thing goes here"]
  }
}

map["errors"]
|> Map.values()
|> List.flatten()
#=> ["example", "something", "thing goes here"]

for {_key, items} <- map["errors"], item <- items, do: item
#=> ["example", "something", "thing goes here"]

Upvotes: 4

Related Questions