Elixir update a particular field in a list of maps

I have this list which has order and order_details. I want to update the quantity field inside order details by subtracting it with the quantity_kot field.

[
  %Od.Orders.Order{
    __meta__: #Ecto.Schema.Metadata<:loaded, "orders">,
    created_at: ~N[2022-02-08 07:05:35],
    email: test@gmail.com,
    name: Test,
    order_details: [
      %Od.Orders.OrderDetails{
        __meta__: #Ecto.Schema.Metadata<:loaded, "order_details">,
        created_at: ~N[2022-02-08 07:05:35],
        discount: 0.0,
        id: "7598503c-88ad-11ec-88f0-027d853babb4",
        price: 10.0,
        quantity: 4.0,
        quantity_kot: 0,
      },
      %Od.Orders.OrderDetails{
        __meta__: #Ecto.Schema.Metadata<:loaded, "order_details">,
        created_at: ~N[2022-02-08 07:05:35],
        discount: 0.0,
        id: "7b9e6d2c-88ad-11ec-83e2-027d853babb4",
        price: 10.0,
        quantity: 3.0,
        quantity_kot: 0,
      }
    ],
    overall_discount: 10.5,
    payment_status: "unpaid",
    updated_at: ~N[2022-02-08 07:05:35],
  }
]

I tried to achieve this by using the below code

[updated_lists] =
  for list <- lists do
    for x <- list.order_details do
        x
        |> Map.update!(:quantity, &(&1 - x.quantity_kot))
    end
  end

updated_lists

These updates but the problem is I am getting only the order details from this result. All the fields in order struct is missing.

I want the whole list back with only the quantity field inside the order details to be updated. Any insight on how to achieve this will be greatly appreciated. Thanks.

your inner iteration is returning only the updated list of order_detail maps. it must return the updated order map

for order <- orders do
    updated_order_details = 
        for order_detail <- order.order_detail do
          Map.update!(order_detail, :quantity, &(&1 - order_detail.quantity_kot))
        end

    %{order | order_details: updated_order_details}
end
2 Likes