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?
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.
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.
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.
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.
Another way: (into {} (map (juxt :categoryname identity) [...]))
(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" }])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With