Find Value of Specific Key in Nested Map

后端 未结 4 701
一向
一向 2021-02-08 09:40

In Clojure, how can I find the value of a key that may be deep in a nested map structure? For example:

(def m {:a {:b \"b\"
            :c \"c\"
            :d {         


        
4条回答
  •  醉酒成梦
    2021-02-08 10:29

    If you know the "path", consider using get-in:

    (get-in m [:a :d :f]) ; => "f"
    

    If the "path" is unknown you can use something like next function:

    (defn find-in [m k]
      (if (map? m)
        (let [v (m k)]
          (->> m
               vals
               (map #(find-in % k)) ; Search in "child" maps
               (cons v) ; Add result from current level
               (filter (complement nil?))
               first))))
    
    (find-in m :f) ; "f"
    (find-in m :d) ; {:e "e", :f "f"}
    

    Note: given function will find only the first occurrence.

提交回复
热议问题