swathi yakkali
swathi yakkali

Reputation: 143

How to convert value of a map to vector in clojure

How do I convert value of a map to vector? For example: {:foo 1 :bar {:foo 1 :bar 2}} to {:foo 1 :bar [{:foo 1 :bar 2}]}

Tried

(for [k (vector (keys m)) :let [m (assoc m :k (vector (:k m)) )] :when (isa? (class (:k m)) clojure.lang.PersistentArrayMap) ] (:k m)) m)

But the map displays without any conversion.Any help is greatly appreciated.

Upvotes: 2

Views: 730

Answers (3)

Mars
Mars

Reputation: 8854

zero323's solution is probably more efficient than mine, but since it can't hurt to know of multiple solutions, here's another in addition to those posted so far:

(zipmap (keys m) 
        (map #(if (map? %) (vector %) %) 
              (vals m)))

Upvotes: 3

guilespi
guilespi

Reputation: 4702

You can try using postwalk to support nested maps.

 (use 'clojure.walk)
 (postwalk (fn [x]
             (if (map? x) (vector x) x))
          {:foo 1 :bar {:foo 1 :bar 2}})

Upvotes: 3

zero323
zero323

Reputation: 330093

How about this:

(into {} (for [[k v] m] [k (if (map? v) [v] v)]))

Upvotes: 3

Related Questions