dan
dan

Reputation: 45652

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 way to do this?

Upvotes: 2

Views: 222

Answers (2)

CubaLibre
CubaLibre

Reputation: 1703

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}))

Upvotes: 0

Leonel
Leonel

Reputation: 29217

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))

Upvotes: 10

Related Questions