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 retrive 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?

Do you want to somehow sum all amounts or it would always be one/first/last or something like that?

It will be always one…

Here is an example code:

defmodule Example do
  def sample(list) when is_list(list) do
    Enum.map(list, fn %{"name" => name, "p" => [%{"amount" => amount}]} ->
      %{amount: amount, name: name}
    end)
  end
end
1 Like

I think, if I understand the question correctly, that it’s necessary to also pattern match to capture the group (A or B), as OP wants a value of nil for all keys associated with group B.

2 Likes
defmodule Example do
  def sample(list) when is_list(list) do
    Enum.map(list, fn %{"name" => name, "p" => [%{"amount" => amount}], "group" => group} ->
      case group do
        "a" -> %{name: name, amount: amount}
        "b" -> %{name: name, amount: nil}
        _ -> # handle cases with no group or some other group
      end
    end)
  end
end
1 Like

Isn’t this the exact same question as before? How to obtain %{key: value} with list with nested map

If you have continuation questions about the same matter, you should use the original topic.

1 Like