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?

-- 
You received this message because you are subscribed to the Google Groups 
"elixir-lang-core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to elixir-lang-core+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/0d7ab3c6-57b1-4f8a-94bd-7bce93cbf5cdn%40googlegroups.com.

Reply via email to