Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure - extract values from a vector of hashmaps

Tags:

clojure

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.

like image 585
Dave Kincaid Avatar asked Apr 19 '11 23:04

Dave Kincaid


2 Answers

(map #(get % "key1") myvec) should be all you need.

like image 168
amalloy Avatar answered Nov 05 '22 14:11

amalloy


(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)))
like image 42
Justin Kramer Avatar answered Nov 05 '22 14:11

Justin Kramer