In clojure, I want to be able to concatenate all the fields(with a separator) in a map for each map in a list.
For the following result I want to be able to get:
(def h '({:key1 "one" :key2 "descone"} {:key1 "two" :key2 "destwo"}))
The result I want:
({one,descone} {two,destwo})
I did the following but I could not get the correct result
(def h '({:key1 "one" :key2"descone"} {:key1 "two" :key2"destwo"}))
(~@(apply interpose "," (map (juxt :key1 :key2) h))))
And I am getting the following instead:
one,desconetwo,destwo
Edit
The scenario is as follows: We use jdbc to make get all the records from postgres. The records are returned like this: ({:col1 "one" :col2 "descone"} {:col1 "two" :col2 "destwo"}). Now, we need to concatenate all the columns with a separator and have this as primary key and insert it back into a new table in postgres.
CodePudding user response:
I'm assuming you want to return a string since you talk about a comma as a separator. I further assume that when you say "all the fields" you mean "all the values of each key-value pair", and that each value is a string. In that case, the following gives you what you wanted.
user> (str "(" (clojure.string/join " " (map #(str "{" (clojure.string/join "," (vals %)) "}") h)) ")")
"({one,descone} {two,destwo})"
user>
What the code is doing is first taking the values of each map and concatenating them with a comma separator and then enclosing each map with an open and close brace. Then it is taking each such string and concatenating them with a space character and then enclosing the whole result with an open and close paren.
EDIT: To match the edit to the question.
Since you want to generate a primary key value that consists of all the value of a database row, what I'm assuming you want to return is a sequence of strings. Where each string is a concatenation, with a separator, of all the values of each map in a specific order. Assuming that is correct, here is a modified answer.
user> (map #(str "{" (clojure.string/join "," ((juxt :key1 :key2) %)) "}") h)
("{one,descone}" "{two,destwo}")
user>