Search code examples
clojureetl

Use For to group maps as one map?


The code I have mostly works but the data isn't in the desired format.

It produces

({"apples" {price 2}}
 {"pears"  {price 4}})

I'd like to be be grouped as one map

{"apples" {price 2}
 "pears"  {price 4}}

This is the code

(defn summarize-many-maps-with-keyname [ms]
  (for [m ms]
    {(first (keys m))
     (summarize-one (first (vals m)))}))

Is there some way to tell for to group them inside a single map? If not, what do you suggest?


Solution

  • How about merging the list of maps?

    (apply merge {} ms)
    

    or the same thing with reduce:

    (reduce into {} ms)
    

    Or, if you insist on using for macro, you can just go through the list of maps and also each entry of each map and dump them into a new map:

    (into {} (for [m ms
                   entry m]
               entry))