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]]) Commented 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. Commented 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.

Sign up to request clarification or add additional context in comments.

3 Comments

Great, thanks... the memory aspect is definitely good to keep in mind!
As for me I find this variant to be better than zipmap, because it is more refactoring-friendly and readable
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.
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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.