fuji
fuji

Reputation: 1203

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.

Upvotes: 1

Views: 317

Answers (3)

mikera
mikera

Reputation: 106361

I'd suggest something like:

(sort-by :name 
  (for [[n m] my-map] 
    (into m {:name n})))

This makes use of a few handy techniques:

  • Destructuring to break my-map into [key value] pairs
  • The fact that you already have maps in the values, so you can use into to add to them
  • A for comprehension to build the list
  • sort-by to sort the final results

Upvotes: 2

amalloy
amalloy

Reputation: 91992

If your goal is to print it in sorted order, why not simply put it into a sorted map? (into (sorted-map) m).

Upvotes: 2

mobyte
mobyte

Reputation: 3752

(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"})

Upvotes: 6

Related Questions