代码之家  ›  专栏  ›  技术社区  ›  Bitwise

用另一个列表替换结构中的列表

  •  1
  • Bitwise  · 技术社区  · 7 年前

    %MyApp.ScoreTable{
      __meta__: #Ecto.Schema.Metadata<:loaded, "score_tables">,
      id: "7f320636-2176-4af2-9207-6251416dd6c2",
      inserted_at: ~N[2018-11-04 21:08:26.024733],
      question: #Ecto.Association.NotLoaded<association :question is not loaded>,
      question_id: "dadc6e57-49f4-4339-9c0f-d40dbc6df534",
      season: #Ecto.Association.NotLoaded<association :season is not loaded>,
      season_id: "c356bae0-bee8-45df-b035-dc117908bebd",
      table_details: %MyApp.TableDetails{
        information: [
          %{
            "team_id" => "7ca4c7ac-850b-4f27-8b6e-1feeb1e0629b",
            "team_score" => "N/A"
          },
          %{"team_id" => "f78c069d-1500-4cfe-a201-13223c417f82", "team_score" => 5},
          %{"team_id" => "4b3459a0-f81c-436d-a68c-3a00dea62a2d", "team_score" => 5},
          %{"team_id" => "9dff5653-dee4-4fef-9d91-7d53f3861275", "team_score" => 10},
          %{"team_id" => "dab53fe6-419b-4a86-a1c6-9c1f65445e12", "team_score" => 15}
        ]
      },
      updated_at: ~N[2018-11-04 21:08:26.024739]
    }
    

    我想完全替换 table_details.information 与此一起列出:

    [
      %{
        "team_id" => "cebda2b5-26e1-4804-8529-17367155db06",
        "team_place" => 1,
        "team_score" => 5
      },
      %{
        "team_id" => "ea800d1c-a079-4f6f-9a91-2a085779dfa9",
        "team_place" => 1,
        "team_score" => 5
      },
      %{
        "team_id" => "2d9253fa-63b7-45dd-bf8f-370598a1424c",
        "team_place" => 3,
        "team_score" => 10
      },
      %{
        "team_id" => "1748f471-08ae-49ed-844b-0fe1bc539a8f",
        "team_place" => 4,
        "team_score" => 15
      },
      %{
        "team_id" => "df2f5102-4e6f-4480-8167-ebe0548cd4ba",
        "team_place" => 5,
        "team_score" => "N/A"
      }
    ]
    

    为了清楚起见,我想用新的地图列表交换旧的列表。我怎样才能做到这一点?

    1 回复  |  直到 7 年前
        1
  •  2
  •   Paweł Obrok    7 年前

    可以使用struct update语法。假设您的整个数据结构都存储在 data 新的名单 new_information ,类似的方法将起作用:

    data = %{data | table_details: %{data.table_details | information: new_information}}
    

    有时候,如果你使用 Access 与相关的 Kernel

    data = put_in(data, [Access.key(:table_details), Access.key(:information)], new_information)
    

    %{other_data.table_details | information: new_information} (注 other_data 而不是 数据