1

Given

[["foo" "bar" 2] ["biz" "baf" 3]] 

how do I get

[{:a "foo" :b "bar" :num 2} {:a "biz" :b "baf" :num 3}]?

In reality my vector has hundreds of vectors that need to have keys added and be converted to hash-maps.

2
  • 4
    something like this: (mapv (partial zipmap [:a :b :num]) [["foo" "bar" 2]["biz" "baf" 3]])
    – leetwinski
    Nov 28, 2017 at 19:29
  • Thanks for this... did the trick! I would have accepted this as the answer but it's a comment do I don't think I can.
    – THX1137
    Nov 28, 2017 at 21:51

2 Answers 2

1

What leetwinski said, or:

(def input [["foo" "bar" 2]["biz" "baf" 3]])

(mapv (fn [[a b num]]
        {:a a
         :b b
         :num num}) input)

If you need to convert a lot of data, maybe mapv is not the best option because it will keep the whole vector in memory at once. Normal map which creates a lazy seq, or a transducer might be better in that case.

3
  • Great, thanks... the memory aspect is definitely good to keep in mind!
    – THX1137
    Nov 28, 2017 at 21:52
  • As for me I find this variant to be better than zipmap, because it is more refactoring-friendly and readable
    – leetwinski
    Nov 29, 2017 at 9:18
  • A minor detail: this way is also more performant than zipmap, but we're talking about 22 vs 220 ns so not likely to be noticed. Nov 29, 2017 at 11:48
0

A general solution:

(defn vectors->maps 
 "takes a vector of vectors containing values and a vector of keys
  and returns a vector of maps such that each value at index n in the value 
  vector is paired with each key at index n in the keys vector
  ex: (vectors->maps [["foo" "bar" 2] ["biz" "baf" 3]], [:a :b :num]) 
         => [{:a "foo", :b "bar", :num 2} {:a "biz", :b "baf", :num 3}]"
  [vectors keys] 
 (mapv (partial zipmap keys) vectors))

Exercise for the reader: writing a spec for this function and generating tests for it to ferret out any edge cases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.