Select keys to form a tupled map in Clojure
Clarice Bouwer
Posted on January 17, 2023
Example:
Taking a vector of maps that looks like
[{:fruit "apple" :color "red" :brand "Granny Smith"}
{:fruit "banana" :color "yellow" :brand "Banana shop"}]
and converting it into {:fruit :color}
({"apple" "red"} {"banana" "yellow"})
Create a hash map from an even list of data
(defn create-hash-map [data] (apply hash-map data))
Output
:> (create-hash-map [1 2 3 4 5 6])
{1 2, 3 4, 5 6}
:> (create-hash-map [1 2 3 4 5])
; Execution error (IllegalArgumentException) at ns/create-hash-map (REPL:31).
; No value supplied for key: 5
Extract a key and value from a map to form a tupled map
(defn tuple [key value data]
(-> data
(select-keys [key value])
(vals)
(create-hash-map)))
Output
:> (tuple :fruit :color {:fruit "apple" :color "red" :brand "Granny Smith"})
{"apple" "red"}
Map through a list of maps to create tuples for each item.
(map
#(tuple :fruit :color %)
[{:fruit "apple" :color "red" :brand "Granny Smith"}
{:fruit "banana" :color "yellow" :brand "South African Bananas"}])
Output
({"apple" "red"} {"banana" "yellow"})
💖 💪 🙅 🚩
Clarice Bouwer
Posted on January 17, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
tutorial Interactive Code Editor Tutorial: Managing Dynamic Content with react-codemirror
October 30, 2024
undefined Como Me Preparei para Trabalhar no Nubank: Minha Jornada de Aprendizagem com Clojure
November 18, 2024