Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a vector of maps to map of maps in Clojure

Tags:

clojure

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?

like image 256
Osman Avatar asked Jun 16 '10 09:06

Osman


People also ask

How do I add and remove map entries in ClojureScript?

The Clojure Cheatsheet is an excellent reference for the functions that we will not be able to cover. ClojureScript has a very helpful pair of functions for adding and removing map entries: assoc and dissoc. Unlike setting and deleting JavaScript object properties, assoc and dissoc do not touch the maps that we supply.

What is a map in CL Clojure?

Clojure - Maps. A Map is a collection that maps keys to values. Two different map types are provided - hashed and sorted. HashMaps require keys that correctly support hashCode and equals. SortedMaps require keys that implement Comparable, or an instance of Comparator.

What are constructors in ClojureScript?

Unlike JavaScript, constructors in ClojureScript are just plain functions that return data. There is no special treatment of constructor functions in the language - they are merely a convenience for us developers to easily create new data while consolidating the creation code in one place.

What is vector of maps in STL?

Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. Vector of Maps in STL: Vector of maps can be used to design complex and efficient data structures.


2 Answers

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

like image 90
kotarak Avatar answered Oct 07 '22 05:10

kotarak


(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" }])
like image 34
Michał Marczyk Avatar answered Oct 07 '22 07:10

Michał Marczyk