Search code examples
dictionaryclojuretraversal

converting nested maps in clojure


I have a nested map which looks something like this:

{"a" {:points 2} "b" {:points 7} "c" {:points 1} "d" {:points 3}}

And I would like to turn it into a sequence of a maps in order to sort (with sort-by) and print it afterwards.

({:name "a" :points 2}
 {:name "b" :points 7}
 {:name "c" :points 1}
 {:name "d" :points 3})

From the documentation I figured that I will need something like postwalk but I can't wrap my head around it.


Solution

  • (sort-by :name
             (map #(conj {:name (key %)}
                          (val %))
                  {"a" {:points 2}
                   "b" {:points 7}
                   "c" {:points 1}
                   "d" {:points 3}}))
    
    -> ({:points 2, :name "a"}
        {:points 7, :name "b"}
        {:points 1, :name "c"}
        {:points 3, :name "d"})