1
votes

I have a Clojure vector of maps used as a lookup table:

(def data 
  [{map1},{map2},...,{nth-map}])

Each map in the vector contains two key/value pairs:

{:key1 "Value1", :key2 "Value2"}

So the entire structure looks like this:

(def data
  [{:key1 "Value1-1", :key2 "Value2-1"}, ; map1
   {:key1 "Value1-2", :key2 "Value2-2"}, ; map2
                     |
                     |
                     V
   {:key1 "Value1-n", :key2 "Value2-n"}]) ; nth-map

I'd like to migrate this into a database table. I already have a function that inserts values into a table row. It takes a single vector with each item in the vector representing a column in the row:

(defn insert-row [column1-value column2-value]
  (sql/with-connection (System/getenv "DATABASE_URL")
    (sql/insert-values
      :table                           ; table name
      [:column1 :column2]              ; table column names
      [column1-value column2-value]))) ; values to be inserted into row

What I need is a function that goes through the entire vector of maps and for each map it creates a vector of just that map's values:

[Value1 Value2]

I think I can use my existing database function insert-row as a parameter to map:

(map insert-row values-from-map)

where values-from-map represents an outer vector containing inner vectors (each containing its respective values) for each map in the original vector:

[[Value1-1 Value2-1]
 [Value1-2 Value2-2]
 [Value1-n Value2-n]]

This would take each vector created and pass it to the insert-values function.

I can create a single vector containing all the values from one keyword:

user=> (vec (map :key1 data))      
["Value1" "Value2" ... "nth=Value"]

How would I create an outer vector containing all the inner vectors?

[[Value1-1 Value2-1][Value1-2 Value2-2]...[Value1-n Value2-n]]
2

2 Answers

6
votes
user=> (vec (for [m data] ((juxt :key1 :key2) m)))
[["Value1-1" "Value2-1"] ["Value1-2" "Value2-2"]]
5
votes

Assuming you still defined your vector of maps as "data":

(into [] (map #(into [] (vals %)) data))