3
votes

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.

2

2 Answers

3
votes

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")
0
votes

If you converted the keys to keywords, perc allows you to do this pretty cleanly:

(->> original-map
  :values
  (mapv #%/%[%:name (dissoc % :name)])
  (into {})
  (#%/%{:values %}))
{:values {"Adhoc" {:sub false}, "Buyer" {:acm true, :list true, :deval true}}}