script
Replace keys from list of maps
I have a list of tuple like this
tuple = [{"id", "provider_id"}, {"cost", "price"}] .
And i have list of maps:
list_of_maps =[
%{cost: 211.0, id: 1},
%{cost: 149.0, id: 2},
%{cost: 247.0, id: 3},
%{cost: 137.0, id: 4},
%{cost: 272.0, id: 5},
%{cost: 150.0, id: 6}
]
I want to replace idwith provider_id and cost with price by using the the list of tuples in this map.
How can it be done?
Thanks
Marked As Solved
grych
To solve (any) issue the best is to divide it into smaller steps.
I’ve created a function replacement_for which returns the corresponding string from tuple, ie. for :id it will return "provider_id" and so on.
Then, the function replace_keys which replaces the keys for the single map.
defmodule R do
defp replacement_for(key, tuple) do
tuple
|> Enum.find(fn {x, _} -> x == to_string(key) end)
|> elem(1)
end
def replace_keys(map, tuple) do
for {k, v} <- map, into: %{}, do: {replacement_for(k, tuple), v}
end
end
All you need to do now, is just use the replace_keys in Enum.map (or for comprehension, as you wish):
Enum.map(list_of_maps, fn m -> R.replace_keys(m, tuple) end)
Also Liked
Eiji
@script: Here is another and also shortest solution I know about:
Enum.map(list_of_maps, & %{price: &1.cost, provider_id: &1.id})
For more information, see:
gausby
Is the key mapping something that needs to change dynamically, because can be done like so:
for %{id: id, cost: cost} <- list_of_maps, do: %{provider_id: id, price: cost}







