更新深层嵌套地图中的单个值

时间:2018-08-26 19:52:38

标签: elixir

我有这张地图:

%{
  __meta__: #Ecto.Schema.Metadata<:loaded, "questions">,
  __struct__: MyApp.Question,
  active: true,
  description: "player points",
  id: 118,
  inserted_at: ~N[2018-08-26 19:48:22.501445],
  reserved: %Statcasters.Questions.Reserved{
    information: %{
      game_id: "b796cbe9-0bb6-4aaf-98b0-5da81c337208",
      player_id: "8ffb69ce-9a6b-44a6-8e8f-c069235d2d31",
      player_name: "Lebron James"
    },
    inputs: [%{label: "Player Points", type: "text"}]
  },
  type: "NBA",
  updated_at: ~N[2018-08-26 19:48:22.504193]
}

如何将reserved.information.player_id8ffb69ce-9a6b-44a6-8e8f-c069235d2d31更新为12345

在Ruby中,由于可变性,这是一个微不足道的变化,但是我很难在Elixir中找到更新它的最佳方法。

当前尝试(无效)

Map.put(map, :player_id, "053600fb-3aae-422f-a9cb-9d102cca301f")

这不起作用,因为它只是将player_id添加到地图的第一级。

3 个答案:

答案 0 :(得分:1)

使用Kernel.put_in/3

input = %{
  reserved: %{
    information: %{player_id: 42}
  }
}

put_in(input, ~w|reserved information player_id|a, -1)
#⇒ %{reserved: %{information: %{player_id: -1}}}

是否要更改/调整值而不是简单地放置新值,请使用Kernel.get_and_update_in/3。为了使后者能够与 struct 一起使用,该结构应实现Access行为。

答案 1 :(得分:1)

  

如何从以下位置更新reserved.information.player_id   8ffb69ce-9a6b-44a6-8e8f-c069235d2d31至12345?

 PURGE BINARY LOGS TO 'mysql-bin-changelog.097019'

在iex中:

defmodule Statcasters.Questions.Reserved do
  defstruct information: %{}, inputs: []
end

defmodule My do

  def go do
    map = %{
      __meta__: "hello world",
      __struct__: "boo hoo",
      active: true,
      description: "player points",
      id: 118,
      inserted_at: ~N[2018-08-26 19:48:22.501445],
      reserved: %Statcasters.Questions.Reserved{
        information: %{
          game_id: "b796cbe9-0bb6-4aaf-98b0-5da81c337208",
          player_id: "8ffb69ce-9a6b-44a6-8e8f-c069235d2d31",
          player_name: "Lebron James"
        },
        inputs: [%{label: "Player Points", type: "text"}]
      },
      type: "NBA",
      updated_at: ~N[2018-08-26 19:48:22.504193]
    }

    put_in(map.reserved.information.player_id, 12345)
  end


end

答案 2 :(得分:0)

假设您的结构存储在名为struct的变量中:

put_in(struct.reserved.information.player_id, "12345")