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
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
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.
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