Wracking my brain this afternoon trying to figure this one out. I'm fairly new to Clojure and Lisp in general. I have a data structure that is a vector of maps and I want to get all the values for a particular key out of all of the maps into another vector.
For example, let's say this is the vector of maps bound to myvec:
[ { "key1" "value1" "key2" "value2"} {"key1" "value3" "key2" "value4"} ]
and I want a vector that looks like
[ "value1" "value3" ]
made up of all the values of the key "key1"
The only way I could think of to do it is
(for [i (range (count(myvec)))] ((myvec i) "key1"))
Is there an easier way? It seems like there must be.
Thanks.
(map #(get % "key1") myvec)
should be all you need.
(let [v [{"key1" "value1", "key2" "value2"} {"key1" "value3", "key2" "value4"}]]
(vec (map #(% "key1") v)))
If you use keywords for your keys:
(let [v [{:key1 "value1", :key2 "value2"} {:key1 "value3", :key2 "value4"}]]
(vec (map :key1 v)))
If you don't want to include nil
values when the maps don't have the given key:
(let [v [{:key1 "value1", :key2 "value2"} {:key1 "value3", :key2 "value4"} {:key2 "value5"}]]
(vec (keep :key1 v)))
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