Skip to content

Like select-keys but for nested maps

License

Notifications You must be signed in to change notification settings

stefanhengl/fields

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

fields Build Status

fields exposes the function select-keys-by-fields which offers the same functionality as select-keys but for complex nested maps. Instead of specifying paths in a vector, we write a query describing the structure of the desired output map.

fieldsis inspired by the same-named HTTP request parameter as described by Google here. In the background it parses the query into a zipper and traverses the zipper filtering the map along the way.

Example

(def data {:a 1
	   :b [{:aa 2 :bb 3} {:aa 4 :bb 5}]
	   :c {:cc 6 :dd {:fff 7 :ggg 8}}})

(select-keys-by-fields data "(a)")
=> {:a 1}

(select-keys-by-fields data "(a,b(aa))")
=> {:a 1, :b ({:aa 2} {:aa 4})}

(select-keys-by-fields data "(b,c(cc,dd(ggg)))")
=> {:b ({:aa 2, ::bb 3} {:aa 4, :bb 5}), :c {:cc 6, :dd {:ggg 8}}}

The parser which parses a query string and outputs a zipper is a pure function that is worth caching whenever you have many differnt maps but only a small set of queries. For such use cases you can just memozie the parser and use select-keys-by-zipper instead of select-keys-by-fields.

(def parse-memo (memoize parse))
(select-keys-by-zipper data (parse-memo "(a,b(aa))"))
=> {:a 1, :b ({:aa 2} {:aa 4})}

Latest Version

Clojars Project

License

MIT