experimentix

experimentix

Update map in loop

Hello

I’m new to elixir and i’m struggling with this problem

I’ve a map lets call it order and that has several products

I want to loop through this products map inside the order map and append some info from another map called associated products

it looks like this

orders map

%{
    "_csrf_token" => "gwsgw",
    "custom_tags" => "",
    "id" => "62212",
    "products" => %{
      "123456" => %{
        "category" => "3",
        "tag" => ["hero", "superstar"],
        "title" => "Product title"
      },
      "234567" => %{"category" => "5", "title" => "Product title"},
	  
      "345678" => %{
        "category" => "8",
        "tag" => ["creation", "dynasty"],
        "title" => "Product title"
      },
      "456789" => %{
        "category" => "5",
        "title" => "Product title"
      },
    },
    "order_id" => "193885",
    "custom_message" => "Nothing to declare",
    "tags_title" => %{"tag" => ["preview"]},
    "allcats" => "5"
  }

associated products map

%{
  "123456" => [
    %{
      "id" => "4984944",
      "has_stock" => false,
      "name" => "Other product Name",
      "product_id" => "123456",
     
    },
    %{
      "id" => "3511064",
      "has_stock" => true,
      "name" => "Other product Name",
      "product_id" => "123456",
     
    }
  ],
  "234567" => [
    %{
      "id" => "3511075",
      "has_stock" => true,
      "name" => "Other product Name",
      "product_id" => "234567",
     
    },
    %{
      "id" => "3511076",
      "has_stock" => false,
      "name" => "Other product Name",
      "product_id" => "234567",
     
    }
  ],
  "345678" => [
    %{
      "id" => "3511082",
      "has_stock" => true,
      "name" => "Other product Name",
      "product_id" => "345678",
     
    },
    %{
      "id" => "3511083",
      "has_stock" => false,
      "name" => "Other product Name",
      "product_id" => "345678",
     
    }
  ]

}

i tried this code to put the associated products but it only gets updated with the last item, i assume its because it doesn’t update the order in every loop

order = for {pid, v} <- order["products"] do
        IO.inspect pid
        IO.inspect v

      order = put_in(order, ["products", pid,"associated_products"], associated_products[pid])

      end

How can i achieve this result??

%{
    "_csrf_token" => "gwsgw",
    "custom_tags" => "",
    "id" => "62212",
    "products" => %{
      "123456" => %{
        "category" => "3",
        "tag" => ["hero", "superstar"],
        "title" => "Product title",
		"associated_products" => [
			%{
			  "id" => "4984944",
			  "has_stock" => false,
			  "name" => "Other product Name",
			  "product_id" => "123456",
			 
			},
			%{
			  "id" => "3511064",
			  "has_stock" => true,
			  "name" => "Other product Name",
			  "product_id" => "123456",
			 
			}
		  ]
		
      },
      "234567" => %{"category" => "5",
		  "title" => "Product title",
		  "associated_products" => [
				%{
				  "id" => "4984944",
				  "has_stock" => false,
				  "name" => "Other product Name",
				  "product_id" => "234567",
				 
				},
				%{
				  "id" => "3511064",
				  "has_stock" => true,
				  "name" => "Other product Name",
				  "product_id" => "234567",
				 
				}
			  ]
	  },
	  
      "345678" => %{
        "category" => "8",
        "tag" => ["creation", "dynasty"],
        "title" => "Product title",
		"associated_products" => [
			%{
			  "id" => "4984944",
			  "has_stock" => false,
			  "name" => "Other product Name",
			  "product_id" => "345678",
			 
			},
			%{
			  "id" => "3511064",
			  "has_stock" => true,
			  "name" => "Other product Name",
			  "product_id" => "345678",
			 
			}
		  ]
      },
      "456789" => %{
        "category" => "5",
        "title" => "Product title",
		"associated_products" => [
			%{
			  "id" => "4984944",
			  "has_stock" => false,
			  "name" => "Other product Name",
			  "product_id" => "456789",
			 
			},
			%{
			  "id" => "3511064",
			  "has_stock" => true,
			  "name" => "Other product Name",
			  "product_id" => "456789",
			 
			}
		  ]
      },
    },
    "order_id" => "193885",
    "custom_message" => "Nothing to declare",
    "tags_title" => %{"tag" => ["preview"]},
    "allcats" => "5"
  }

Marked As Solved

stefanluptak

stefanluptak

Check this gist: update_map_in_loop.md · GitHub
It’s a Livebook, so you can copy and paste it into your Livebook server and play with it.

If you need more explanation, I can provide it. I am pretty sure there are more elegant ways to achieve this, but this should be good enough as a start.

The problem with your solution is that it’s not “reducing” the order (keeping the changes for all iterations), just returning the list of modified orders. Each order (item of the returned list) is the order modified but just for a single product.

Hope this helps a bit.

Also Liked

experimentix

experimentix

Thank you very much, it worked. And thanks for small explanation.

I think i understand how things work now looking at your code.

Once again thanks

experimentix

experimentix

Since my associated products has the key same as the product key i ended with removing some of your code and referencing it like this

Enum.reduce(order["products"], order, fn {product_id, _product}, order ->
   update_in(order, ["products", product_id], fn product ->
    Map.put(product, "associated_products", associated_products[product_id])
  end)
end)

Once again thanks

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
JeremM34
Hello, how can I check the Phoenix version ? Thanks !
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
fireproofsocks
I’m working on defining a simple Ecto schema for a table (in PostGres), but I don’t see where I can define a column as NOT NULL. Conside...
New
vac
Hi, I’m quite new in Elixir and I’m trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and I...
New
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; somethi...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
hariharasudhan94
I would like to know what is the best IDE for elixir development?
New
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New

Other popular topics Top

vertexbuffer
Hello, can anybody help here..? I have a list of players and I what to delete an element, but every for loop the list is reverting to ori...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
johnnyicon
Hi all, I’ve just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I’m trying to use Postgres...
New
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
Lily
In templates/appointment/index.html.eex: &lt;%= for appointment &lt;- @appointments do %&gt; &lt;tr&gt; &lt;td&gt;&lt;%= appoi...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
RisingFromAshes
I’ve read in another post that it may be possible with a router helper - but I couldn’t find an appropriate one, and tbh, I’m still just ...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 records...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

We're in Beta

About us Mission Statement