tags:

views:

108

answers:

3

Hi,

I've a vector of maps like this:


[
 {:categoryid 1, :categoryname "foo" } 
 {:categoryid 2, :categoryname "bar" } 
 {:categoryid 3, :categoryname "baz" }
]

and would like to generate a map of maps like this for searching by categoryname


{
"foo" {:categoryid 1, :categoryname "foo" }, 
"bar" {:categoryid 2, :categoryname "bar" }, 
"baz" {:categoryid 3, :categoryname "baz" }
}

How can i achieve?

+5  A: 
(reduce (fn [m {catname :categoryname :as input}]
          (assoc m catname input))
        {}
        [{:categoryid 1, :categoryname "foo" } 
         {:categoryid 2, :categoryname "bar" } 
         {:categoryid 3, :categoryname "baz" }])

Better yet,

(#(zipmap (map :categoryname %) %)
 [{:categoryid 1, :categoryname "foo" } 
  {:categoryid 2, :categoryname "bar" } 
  {:categoryid 3, :categoryname "baz" }])
Michał Marczyk
Second way is realy cool.Thanks @Michal.
Osman
A: 
(ns code.groupby
  (:use clojure.contrib.seq-utils))


(def vector-of-maps [ {:categoryid 1, :categoryname "foo" }
                      {:categoryid 2, :categoryname "bar" }
                      {:categoryid 3, :categoryname "baz" } ])

(group-by :categoryname vector-of-maps)

Gives you a map of Vectors of maps

{"bar" [{:categoryid 2, :categoryname "bar"}],
 "baz" [{:categoryid 3, :categoryname "baz"}],
 "foo" [{:categoryid 1, :categoryname "foo"}]}

(which I now realise isn't what you wanted...sorry)

tim_yates
+2  A: 

Another way: (into {} (map (juxt :categoryname identity) [...]))

kotarak
nice use of juxt :)
tim_yates