elSnape
elSnape

Reputation: 302

adding a key to vector of values in Clojure

I have a vector of strings (although could be anything really), and I want to create a new vector of map entries, with the key being some keyword.

For example, given:

["foo" "bar" "baz"]

I want to get

[{:message "foo"} {:message "bar"} {:message "baz"}]

What is the most idiomatic way of applying this transformation?

Thanks!

Upvotes: 2

Views: 944

Answers (2)

clojureman
clojureman

Reputation: 431

I think A. Webb presents some very good options.
My suggestion would be to go for readability for a broad audience:

 (mapv (fn[x] {:message x}) ["foo" "bar" "baz"])

Also, if you don't need a vector,

 (map (fn[x] {:message x}) ["foo" "bar" "baz"])

will be readable to even more people.

Upvotes: 2

A. Webb
A. Webb

Reputation: 26436

That's a matter of opinion. Some options:

 (into [] (for [x ["foo" "bar" "baz"]] {:message x}))

 (mapv hash-map (repeat :message) ["foo" "bar" "baz"])

 (mapv (partial assoc {} :message) ["foo" "bar" "baz"])

 (reduce #(conj % {:message %2}) [] ["foo" "bar" "baz"])

Upvotes: 7

Related Questions