Clojure - extract values ​​from hashpap vector

This morning my brain is trying to figure out how to do this. I am new to Clojure and Lisp in general. I have a data structure, which is a map vector, and I want to get all the values ​​for a particular key from all maps in another vector.

For example, suppose this is a vector of cards associated with myvec:

[ { "key1" "value1" "key2" "value2"} {"key1" "value3" "key2" "value4"} ] 

and i need a vector that looks like

 [ "value1" "value3" ] 

consisting of all key values ​​"key1"

The only way I could do this is

 (for [i (range (count(myvec)))] ((myvec i) "key1")) 

Is there an easier way? It seems like it should be.

Thanks.

+6
source share
2 answers

(map #(get % "key1") myvec) should be all you need. Consider using keywords instead of “strings” as keys, although in general it is better and more idiomatic. Alternatively, you could write it as simply (map :key1 myvec)

+17
source
 (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 do not want to include nil values ​​when the cards do not have a given key:

 (let [v [{:key1 "value1", :key2 "value2"} {:key1 "value3", :key2 "value4"} {:key2 "value5"}]] (vec (keep :key1 v))) 
+8
source

Source: https://habr.com/ru/post/886280/


All Articles