替换长生不老药中的数组中的项目 [英] Replace item in an array in elixir

查看:65
本文介绍了替换长生不老药中的数组中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一张看起来像这样的地图

Let's say I have a map that looks like this

一个组织具有一组属性,而这些属性具有一组 access_tokens

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"}]
    }
  ]
}

现在我有了这张地图,对于一个特定的访问令牌,此ID的ID与第二个属性的访问令牌之一匹配:

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"}

迭代使用新访问令牌更新 organization%{} 映射的最佳方法是什么?我想做的是找到基于 id 匹配的访问令牌,并将其替换为具有新名称的新令牌。

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.

我有一些解决方法,但是在Elixir中这样做是一种干净的方法。

I have some round-about ways of doing this, but what is a clean way to do this in Elixir.

推荐答案

您无需进行迭代,只需使用 Access Access.filter / 1 Access.all / 0

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.

这篇关于替换长生不老药中的数组中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆