C.A
C.A

Reputation: 620

Transform nested clojure maps

I am having trouble transforming a clojure map. The map has a vector as element and the vectors in turn have maps as elements.

The original map looks like this:

{"values" [{"sub" false, "name" "Adhoc"} {"acm" true, "list" true, "deval" true, "name" "Buyer"}]}

The maps within the vector always have the key "name" but the other keys may vary. The name element should act as a key within the map. As end result I need the original map to be transformed into this:

{"values" {"Adhoc" {"sub" false}, "Buyer" {"deval" true, "acm" true, "list" true}}

The problem is that the maps within the vector can have any amount of elements and I don't really know how to solve that with looping. Any suggestions would be highly appreciated.

Upvotes: 3

Views: 960

Answers (1)

xsc
xsc

Reputation: 6073

This would process the vector of maps for you:

(defn merge-by
  [maps k]
  (->> maps
       (map (juxt #(get % k) #(dissoc % k)))
       (into {})))

(merge-by [{"sub" false, "name" "Adhoc"} 
           {"acm" true, "list" true, "deval" true, "name" "Buyer"}] 
          "name")
;; => {"Adhoc" {"sub" false}, "Buyer" {"deval" true, "acm" true, "list" true}}

And this would process the outer map (if stored in my-map):

(update-in my-map ["values"] merge-by "name")

Upvotes: 3

Related Questions