Elixir:更新地图列表中的特定值 [英] Elixir: Update a specific value in a list of maps
问题描述
给出以下地图列表:
ball_prop_list =
[
%{"id" => "cue", "is_idle" => true, "velocity_x" => 0.0, "velocity_z" => 0.0, "x" => -15.0, "z" => 0.0},
%{"id" => "ball_1", "is_idle" => true, "velocity_x" => 0.0, "velocity_z" => 0.0, "x" => 15.0, "z" => 0.0},
%{"id" => "ball_2", "is_idle" => true, "velocity_x" => 0.0, "velocity_z" => 0.0, "x" => 17.0, "z" => 1.1},
%{"id" => "ball_3", "is_idle" => true, "velocity_x" => 0.0, "velocity_z" => 0.0, "x" => 17.0, "z" => -1.1}
]
我该如何更改例如"id"的
,并保持其他所有内容不变? velocity_x
和 velocity_y
?=>提示"
How do I go about changing, say, just the velocity_x
and velocity_y
of "id" => "cue"
, and keeping everything else the same?
我只是尝试创建一个具有更新值的新列表(这不一定是我的目标),如下所示:
I've only gotten as far as trying to create a new list (which was not necessarily my goal) with updated values, such as the following:
new_prop_list = Enum.map(balls_json_list, fn(val) ->
if val["id"] == "cue" do
Map.put(val, "velocity_x" velocity_vector[:x])
Map.put(val, "velocity_z" velocity_vector[:z])
end
end)
但这并没有解决,可能是因为我的地图没有使用原子键-到目前为止,我看到的所有其他示例都使用原子键,或者添加了新的键和值,等等.
But this didn't work out, probably because my maps do not use atom keys - every other example I've seen so far uses atom keys, or adds a new key and value, etc.
还有什么我可以尝试的吗?
Is there anything else I can try?
推荐答案
Map.put/3
不会就地修改地图(因为无法修改Elixir中的数据结构),但是创建一个新地图.
Map.put/3
does not modify the map in-place (because no data structure in Elixir can be modified), but creates a new map.
还,您错过了两个逗号.
Also, you missed 2 commas.
new_ball_prop_list = Enum.map(ball_prop_list, fn
%{"id" => "cue"} = map ->
map
|> Map.put("velocity_x", velocity[:x])
|> Map.put("velocity_y", velocity[:y])
other_map ->
other_map
end)
您还可以尝试 Map.merge/2
或%{map |k1 =>v1,k2 =>v2}
这篇关于Elixir:更新地图列表中的特定值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!