将值重新分配给列表Elixir

时间:2016-09-12 15:32:22

标签: list enums elixir

我有一个结构(数据),其中真实值取决于客户发出请求,但我无法重新分配它们。这是我的代码:

基础结构:

Party: [
  Sender: [

  ]
]

关于客户真实价值的一个例子:

Party: [
  Sender: [
    AgentUserSender: [
      Name: "The_name",
      Type: "The_type",
      OtherIDs: [
        {:OtherID, %{Description: "value"}, "_value"},
        {:OtherID, %{Description: "value_1"}, "_value_1"}
      ],
      OtherKey: "other_value"
    ]
  ]
]

我(很差)试图做的事情:

data[:Party][:Sender] = customer[:Party][:Sender]

还有一个问题:并非所有客户在结构上都有相同的字段。这是其他客户的另一个例子:

Party: [
  Sender: [
    TravelAgencySender: [
      Name: "NAME",
      IATA_Number: "xxxxxxxx",
      AgencyID: "agency"
    ]
  ]

非常感谢。

2 个答案:

答案 0 :(得分:1)

我相信你想要做的是:

> data = [Party: [Sender: []]]
[Party: [Sender: []]]
> data = put_in(data[:Party][:Sender], ["something"])
[Party: [Sender: ["something"]]]

或者这个:

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

答案 1 :(得分:0)

最直接的方法是使用Keyword.get_and_update/3

{ sender, cust[:Party][:Sender] }

如果要合并值或以某种复杂方式修改它,只需修改

即可
fminsearch

返回第二个元组项所需的行(第一个是得到的值,因此保持不变。)