Daniel Wu
Daniel Wu

Reputation: 6003

how to convert list to map in clojure

I have the following list

({:Col1 {:type varchar :nullable true}} {:Col2 {:type varchar :nullable true}} {:Col3 {:type varchar :nullable false}})

And want to convert to the following

{:Col3 {:type varchar, :nullable false}, :Col1 {:type varchar, :nullable true}, Col2 {:type varchar, :nullable true}}

I am using the following code.

(def a '({:Col1 {:type varchar :nullable true}} {:Col2 {:type varchar :nullable true}} {:Col3 {:type varchar :nullable false}}))

 (apply hash-map (flatten (map (comp flatten seq) a)))

But is there any better solutions?

Upvotes: 1

Views: 811

Answers (2)

Mars
Mars

Reputation: 8854

In addition to Symfrog's answer, this option is equally short, but may be a little bit easier to understand:

(apply merge a)

where a is defined as a sequence of maps, as in your question.

You can also use

(reduce conj a)

which is roughly how merge is defined in the Clojure source.

Upvotes: 0

Symfrog
Symfrog

Reputation: 3418

An alternative is to use merge:

(reduce merge
        '({:Col1 {:type varchar :nullable true}} {:Col2 {:type varchar :nullable true}} {:Col3 {:type varchar :nullable false}}))

Upvotes: 3

Related Questions