I've found myself repeatedly need to replace some key name in the map.
For example, to change the key name from "_id" to "id":
data = fetch_some_data_from_db()
{id, data} = Map.pop(data, "_id")
data |> Map.put(data, "id", id)
It gets messy when the target is deeply nested.
To help deal with it, I wrote two util functions:
defp replace_key_in(data, [old_name], new_name),
do: replace_key(data, old_name, new_name)
defp replace_key_in(data, [_ | _] = path, new_name) do
{path, [old_name]} = Enum.split(path, -1)
update_in(
data,
path,
&replace_key(&1, old_name, new_name)
)
end
defp replace_key(data, old_name, new_name) do
{value, rest} = Map.pop(data, old_name)
Map.put(rest, new_name, value)
end
Do you think we can add it to the Map module?