开发者

How do I transform a sequences of maps into a sequence of maps with selected keys?

I have a sequence of map like this

({:a 1 :b 2 : c 4} {:a 3 :b 3 :d 4})

And I want to turn this into a sequence of more compact maps that just have the :a and :b keys, like this:

({:a 1 :b 2} {:a 3 :b 3})

What's the most concise w开发者_JAVA技巧ay to do this?


The built-in function select-keys is what you're looking for.

(let [in [{:a 1 :b 2 :c 4} {:a 3 :b 3 :d 4}]]
  (map #(select-keys % [:a :b])
       in))


A more generic solution would be to write a function that takes the keys you want to keep and returns a fn on maps. Then map it over the sequence of maps:

(defn keep-keys
  [ks]
  (fn [m] (select-keys m ks)))

(map (keep-keys [:a :b]) '({:a 1 :b 2 :c 4} {:a 3 :b 3 :d 4}))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜