shmish111
shmish111

Reputation: 3787

how to navigate a map in clojure in a similar way to threading

Is there a nicer way to navigate though a nested map in clojure. E.g. for the following map:

{
  :one{
    :two {
      :three value
     }
   }
}

To get the value of :three I do (:three (:two (:one mymap))) but it would be much nicer if there was something like threading where I could do (-> mymap :one :two :three)

Upvotes: 2

Views: 337

Answers (2)

A. Webb
A. Webb

Reputation: 26446

"it would be much nicer if there was something like threading where I could do (-> mymap :one :two :three)"

Who says you can't? Your exact syntax works!

so.core=> (def mymap { :one, { :two, { :three :value } } })
#'so.core/mymap
so.core=> (-> mymap :one :two :three)
:value

Upvotes: 7

tangrammer
tangrammer

Reputation: 3061

The core function get-in fits exactly your requirement

Returns the value in a nested associative structure,
where ks is a sequence of ke(ys. Returns nil if the key is not present,
or the not-found value if supplied.


(get-in your-nested-data [:one :two :three])

http://clojuredocs.org/clojure_core/clojure.core/get-in

Upvotes: 6

Related Questions