Hello… I have a output like
%{
"name" => "A",
"price_per_unit_in_cents" => nil,
"price_point_count" => 1,
"prices" => [
%{
"quantity" => nil,
"formatted_unit_price" => "$10.00",
"c_quantity" => 1,
"unit_price" => "10.0"
}
],
"pricing_scheme" => "per_unit",
},
%{
"name" => "B",
"price_per_unit_in_cents" => nil,
"price_point_count" => 1,
"prices" => [
%{
"quantity" => nil,
"formatted_unit_price" => "$14.95",
"c_quantity" => 1,
"unit_price" => "14.95"
}
],
"pricing_scheme" => "per_unit",
},
%{
"name" => "C",
"price_per_unit_in_cents" => nil,
"price_point_count" => 1,
"prices" => [
%{
"quantity" => nil,
"formatted_unit_price" => "$22.95",
"c_quantity" => 1,
"unit_price" => "22.95"
}
],
"pricing_scheme" => "per_unit",
}
I want to loop through each map so that I can have final output as
[
%{formatted_unit_price: "$20.00"},
%{formatted_unit_price: "$10.00"},
%{formatted_unit_price: "$30.00"}
]
Can anyone help me??
NobbZ
2
If there is more than one entry in "prices"
, how do you want to handle that?
1 Like
“Prices” will always have one entry.
NobbZ
4
Why is it a list then? And named in plural form?
Anyway, you can use Enum.map/2
and a pattern match in the anonymous function then:
Enum.map(input, fn %{"prices" => [%{"formatted_unit_price" => fup}]} ->
%{formatted_unit_price: fup}
end)
2 Likes
Okay… will change those names… Thank you again
NobbZ
6
If you change the structure, my pattern match won’t work anymore ;).
1 Like
NobbZ
8
Should be easy to adjust though, if you get how pattern matches work.
1 Like
Just trying to understand things better… 
NobbZ
10
Which things exactly? We are happy to help and explain!
Open a new topic if you feel its different enough from your current topic.
2 Likes
if your data is list of maps
[
%{
"name" => "A",
"price_per_unit_in_cents" => nil,
"price_point_count" => 1,
"prices" => [
%{
"c_quantity" => 1,
"formatted_unit_price" => "$10.00",
"quantity" => nil,
"unit_price" => "10.0"
}
],
"pricing_scheme" => "per_unit"
},
%{
"name" => "B",
"price_per_unit_in_cents" => nil,
"price_point_count" => 1,
"prices" => [
%{
"c_quantity" => 1,
"formatted_unit_price" => "$14.95",
"quantity" => nil,
"unit_price" => "14.95"
}
],
"pricing_scheme" => "per_unit"
},
%{
"name" => "C",
"price_per_unit_in_cents" => nil,
"price_point_count" => 1,
"prices" => [
%{
"c_quantity" => 1,
"formatted_unit_price" => "$22.95",
"quantity" => nil,
"unit_price" => "22.95"
}
],
"pricing_scheme" => "per_unit"
}
]
Enum.each(d,fn(m)-> Map.get(m, "prices") |> Enum.each(fn %{"formatted_unit_price" => price } -> IO.inspect(%{"formatted_unit_price": price}) end) |> IO.inspect end)
1 Like