THX1137
THX1137

Reputation: 973

how to remove a given key from a series of maps in a vector in clojure?

In clojure, given a data structure [{:a "foo" :b "bar"} {:a "biz" :b "baz"}] how would I get [{:b "bar"}{:b "baz"}] the most succinctly?

Upvotes: 1

Views: 770

Answers (2)

Shivam
Shivam

Reputation: 1116

@Taylor's above answer to dissoc :a from each map is fine if you want all maps without :a.

In case if you want a list of maps with just :b key, you can do

<!-- language-all: lang-clj -->

;; Assuming my-map is the object map
;; map returns a lazy sequence

(map #(hash-map :b (:b %)) my-map)

;; or
(map #(select-keys % [:b]) mp)

Upvotes: 2

Taylor Wood
Taylor Wood

Reputation: 16194

dissoc is a function for dissociating a key from an associative structure like a map. Here's how you'd do it with one map:

(dissoc my-map :a)

If you have a sequence of maps, you can map a function over them to dissoc the key(s) from each map:

(map #(dissoc % :a) the-maps)

This phrasing passes an anonymous function to map, but depending on usage you may want to extract a named function:

(defn fix-the-map [m]
  (dissoc m :a))

(map fix-the-map the-maps)

Upvotes: 8

Related Questions