You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用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 multiple assoc calls here, though that would work too if you prefer it).
  • conj appends this new map to the accumulator vector—this is the right tool for adding elements to a collection like a vector, unlike merge which 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:14:41