How to update a mapset

If I have a MapSet in the form:

#MapSet <[
    %{
        author: 1234,
        comments: [
        %Other.Module {
            body: "I WANT TO UPDATE THIS",
            other_key: 123,
            ...
        }
        ],
        other_key: 234,
        ...
    }
]>

How can I update the body?

1 Like

You have a mapset, that contains a map, that contains a list, with a struct You want to transform…

You should tell how You get this data, because it’s probably easier to treat this when it is build.

        %Other.Module {
            body: "I WANT TO UPDATE THIS",
            other_key: 123,
            ...
        }

You should start by knowing how to procede with this simple transformation, then later You could decompose the more complex structure.

1 Like

Can you elaborate on your use of MapSets? Updating inner items isn’t a particularly normal access pattern.

Since the MapSet type is opaque I think you probably should be creating a new MapSet, not trying to mutate an existing one. The type is:

  @opaque t(value) :: %__MODULE__{map: %{optional(value) => []}}
  @type t :: t(term)

Even though the MapSets structure is opaque and has to be treated unknown, we can Access it or use Enum.

So the main question is probably, which of the potentially many bodies in such a set should be changed? If it’s only one, then put_in/get_in are probably of help, if it’s all, Enum.map.

1 Like

I recommend using the MapSet public API: remove the target item from the MapSet with MapSet.delete/2 followed by MapSet.put/2 with the updated value.

You’re right. After digging around the source a bit more I came to find where the map was being created and found it far easier to just modify it from the starting point.