Clojure 101 combining vectors into a map

I am very new to Clojure and cannot find a way to do something that I'm sure is trivial. I looked at the function assoc, as I think it may be the answer, but cannot make it work.

What I have:

keys => [:num, :name, :age]
people =>  [ [1, "tim", 31] [2, "bob" 33] [3, "joe", 44] ]

I want to create a map vector, each map will look like

[ { :num 1, :name "tim", :age 31 } 
  { :num 2, :name "bob", :age 33 } 
  { :num 3, :name "joe", :age 44 } ]

My OO brain wants me to write a bunch of loops, but I know that there is a better way that I just lost a little in the big API.

+5
source share
2 answers

Try the following:

(def ks [:num :name :age])
(def people [[1 "tim" 31] [2 "bob" 33] [3 "joe" 44]])

(map #(zipmap ks %) people)

=> ({:num 1, :name "tim", :age 31}
    {:num 2, :name "bob", :age 33}
    {:num 3, :name "joe", :age 44})

, ks keys , keys Clojure, . , map ; , :

(vec (map #(zipmap ks %) people))

=> [{:num 1, :name "tim", :age 31}
    {:num 2, :name "bob", :age 33}
    {:num 3, :name "joe", :age 44}]
+10

, clojure.core/partial:

(map (partial zipmap keys) people)

, keys.

+1

All Articles