[英]Reassign value to a list Elixir
I have a structure (data) where the real values are dependent about the customer is making the request, but I am not able to reassign them.我有一个结构(数据),其中真实值取决于客户提出请求,但我无法重新分配它们。 This is my code:
这是我的代码:
The base structure:基础结构:
Party: [
Sender: [
]
]
And an example about the real values of a customer:以及一个关于客户真实价值的例子:
Party: [
Sender: [
AgentUserSender: [
Name: "The_name",
Type: "The_type",
OtherIDs: [
{:OtherID, %{Description: "value"}, "_value"},
{:OtherID, %{Description: "value_1"}, "_value_1"}
],
OtherKey: "other_value"
]
]
]
And how I (poorly) trying to do:以及我如何(糟糕地)尝试做:
data[:Party][:Sender] = customer[:Party][:Sender]
There is another added problem: not all customers has the same fields on the structure.还有另一个问题:并非所有客户在结构上都有相同的字段。 This is other example, of other customer:
这是其他客户的其他示例:
Party: [
Sender: [
TravelAgencySender: [
Name: "NAME",
IATA_Number: "xxxxxxxx",
AgencyID: "agency"
]
]
Thank you very much.非常感谢。
I believe what you want to do is this:我相信你想做的是这样的:
> data = [Party: [Sender: []]]
[Party: [Sender: []]]
> data = put_in(data[:Party][:Sender], ["something"])
[Party: [Sender: ["something"]]]
or this:或这个:
> data = [Party: [Sender: ["something"]]]
[Party: [Sender: ["something"]]]
> data = put_in(data[:Party][:Sender], data[:Party][:Sender] ++ ["something_else"])
[Party: [Sender: ["something", "something_else"]]]
#Alternatively update_in instead of put_in
> data = [Party: [Sender: ["something"]]]
[Party: [Sender: ["something"]]]
> data = update_in(data[:Party][:Sender], &(&1 ++ ["something_else"]))
[Party: [Sender: ["something", "something_else"]]]
The most straightforward way would be to use Keyword.get_and_update/3
:最直接的方法是使用
Keyword.get_and_update/3
:
iex(1)> mine = [Party: [ Sender: [ ]]]
iex(2)> cust = [Party: [ Sender: [ .......... ]]]
iex(3)> { _, data } = mine |> Keyword.get_and_update(:Party, fn party ->
...(3)> { _, result } = mine[:Party]
...(3)> |> Keyword.get_and_update(:Sender, fn sender ->
...(3)> { sender, cust[:Party][:Sender] }
...(3)> end)
...(3)> { party, result }
...(3)> end)
iex(4)> data
[Party: [Sender: [AgentUserSender: [Name: "The_name", Type: "The_type",
OtherIDs: [{:OtherID, %{Description: "value"}, "_value"},
{:OtherID, %{Description: "value_1"}, "_value_1"}],
OtherKey: "other_value"]]]]
If you want to merge values, or modify it in some sophisticated way, just modify如果您想合并值,或以某种复杂的方式修改它,只需修改
{ sender, cust[:Party][:Sender] }
line to return what is needed as second tuple item (the first is to be the value got, and hence is to be left intact.)行返回作为第二个元组项目所需的内容(第一个是获得的值,因此保持不变。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.