11

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 do this?

4 Answers 4

16

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

1
(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)

Comments

0

I haven't tested it in Clojure, but in ClojureScript this variant appears to be faster than others:

(reduce #(assoc %1 (:categoryname %2) %2) {} [...]) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.