开发者

Clojure - extract values from a vector of hashmaps

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 th开发者_开发百科at 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)))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜