Reputation: 2523
Let's say I have a map that looks like this
An organization has an array of properties and the properties has an array of "access_tokens"
organization = %{
name: "Org",
properties: [
%{
name: "prop1",
access_tokens: [%{id: "at-1", name: "one-1"}, %{id: "at-2", name: "one-2"}]
},
%{
name: "prop2",
access_tokens: [%{id: "at-3", name: "two-1"}, %{id: "at-4", name: "two-2"}]
}
]
}
Now I have this map, for one particular access token, the id for this one matches one of the access tokens for the 2nd property:
access_token = %{id: "at-3", name: "new name"}
What is the best way to iterate over to update the organization%{}
map with the new access token? What I want to do is find the access token that matches based on id
and replace it with the new one that has the new name.
I have some round-about ways of doing this, but what is a clean way to do this in Elixir.
Upvotes: 3
Views: 2051
Reputation: 121010
You do not need to iterate, just use Access
, Access.filter/1
, and Access.all/0
:
put_in(
organization,
[:properties,
Access.all(),
:access_tokens,
Access.filter(&match?(%{id: "at-3"}, &1)),
:name],
"new_name")
I always wonder, how this one of the most powerful things in the language is extremely underrated.
Upvotes: 14