Adding to nested associative structures

I have a structure that I created in REPL,

{1 {10 {:id 101, :name "Paul"}, 20 {}}, 2 {30 {}, 40 {}}, 3 {50 {}, 60 {}}} 

and I want to add a new kv to key 1 so that the resulting structure looks like this:

 {1 {10 {:id 101, :name "1x2"}, 20 {}, 11 {:id 102, :name "Ringo"}}, 2 {30 {}, 40 {}}, 3 {50 {}, 60 {}}}. 

I just opened get-in update-in and assoc-in to work with such nested structures, but I can’t figure out how to add new elements to elements. In my application, this is all wrapped in ref and updated by dosync / alter, but for now I just want to be able to do this on REPL.

I may have just looked at this for too long, but any attempt to use an associative or associative interface simply modifies what already exists and does not add new elements.

+4
source share
2 answers

Given your input

 (def input {1 {10 {:id 101 :name "Paul"} 20 {}} 2 {30 {} 40 {}} 3 {50 {} 60 {}}}) 

You can use an additional item to add an item to a nested map with key 1 as follows:

 (assoc-in input [1 11] {:id 102 :name "Ringo"}) 

what gives

 {1 {10 {:id 101 :name "Paul"} 11 {:id 102 :name "Ringo"} 20 {}} 2 {30 {} 40 {}} 3 {50 {} 60 {}}} 

The interaction does not need to indicate the deepest level of structure.

If you use two calls to connect, you can use the second to change the name "Gender" to "1x2" according to your example:

 (assoc-in (assoc-in input [1 11] {:id 102 :name "Ringo"}) [1 10 :name] "1x2")) 

What returns

 {1 {10 {:id 101 :name "1x2"} 11 {:id 102 :name "Ringo"} 20 {}} 2 {30 {} 40 {}} 3 {50 {} 60 {}}} 
+7
source

Why can you do this anyway if you had to point to an existing node:

 (update-in input [1] assoc 11 {:id 102 :name "Ringo"}) 
+1
source

All Articles