如何用reduce-kv和assoc将Map转换为Map数组?
Solution to Convert Clojure Map to Map Array
Got it, let's get this sorted for you! You're absolutely on the right path with reduce-kv—the main tweak needed is how you build up the resulting vector instead of trying to merge maps into it. Here's the working code:
(reduce-kv (fn [acc k v] (conj acc {:newKey1 k :newKey2 v})) [] {"keystring1" "valuestring1" "keystring2" "valuestring2"})
Breakdown of what's happening:
- We start with an empty vector
[]as our accumulator—this aligns perfectly with your goal of ending up with an array (vector) of maps. - For every key-value pair in the original map, we create a new map directly using the shorthand
{:newKey1 k :newKey2 v}(no need for multipleassoccalls here, though that would work too if you prefer it). conjappends this new map to the accumulator vector—this is the right tool for adding elements to a collection like a vector, unlikemergewhich is for combining maps together.
What was off in your initial attempt?
Your original code tried to merge maps into the accumulator, but merge operates on maps, not vectors. Since we're building a list of maps, conj is the correct function to use here to grow the vector incrementally.
If you run the code above, you'll get exactly the output you want:
[{:newKey1 "keystring1", :newKey2 "valuestring1"} {:newKey1 "keystring2", :newKey2 "valuestring2"}]
内容的提问来源于stack exchange,提问作者Jdv
相关产品推荐
相关产品推荐

