Replace item in an array in elixir

瘦欲@ 提交于 2019-12-24 16:42:51

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/58822023/replace-item-in-an-array-in-elixir

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!