Search code examples
clojure

Conditionally rename keys in a list and convert into a map?


Is there a simple way to convert a list of key-values into a map while also renaming the keys in a conditional way?

Example:

 [{:count 4, :happened "true"} {:count 1, :happened "false"}]

converted into:

{:happened-count: 4, :didnt-happen-count: 1}

I'm kinda close:

user=> (def foo [{:count 4, :happened "true"} {:count 1, :happened "false"}])

user=> (into {} (map (juxt :happened :count) foo))
{"true" 4, "false" 1}

edit: This works, but it is ugly. Hoping for something nicer:

(clojure.set/rename-keys (into {} (map (juxt :happened :count) foo)) {"true" :happened-count "false" :didnt-happen-count})

Solution

  • i would rather advice using simple reduction

    (def mapping {"true" :happened-count "false" :didnt-happen-count})
    
    (reduce #(assoc % (-> %2 :happened mapping) (:count %2)) {} data)
    
    ;;=> {:happened-count 4, :didnt-happen-count 1}