VR_1
VR_1

Reputation: 153

Get %{key,value} from list of map

I have list with nested map

[ %{
    "name" => "sam",
    "p" => [
      %{
        "amount" => "$10",
      }
    ],
    "group" => "a",   
},   
%{
    "name" => "lisa",
    "p" => [
      %{
        "amount" => "$20",
      }
    ],
    "group" => "a",   
}, 
 %{
    "name" => "joe",
    "p" => [
      %{
        "amount" => "$30",
      }
    ],
    "group" => "b",   
} ]

I have to loop through the list to get the name as well amount from the list in such a way that if group is a then retrieve the amount , otherwise put nil to the map. So that the final list can look like

[
  %{name: "sam",amount: "$10"},
  %{name: "lisa", amount: "$20"},
  %{name: "joe", amount: nil}
]

Can anyone please help me with this?

Upvotes: 0

Views: 762

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121000

You need to map your elements, hence Enum.map/2 with different function clauses matching different cases seems to be the best fit.

Enum.map(data, fn
  %{"group" => "a", "name" => name, "p" => [%{"amount" => amount}]} ->
    %{name: name, amount: amount}

  %{"name" => name} ->
    %{name: name, amount: nil}
end)
#⇒[
#   %{amount: "$10", name: "sam"},
#   %{amount: "$20", name: "lisa"},
#   %{amount: nil, name: "joe"}
# ]

Upvotes: 2

Related Questions