Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decompose nested maps into key-value pairs

Tags:

clojure

I would like to decompose a nested map in Clojure into a sequence of key-value pairs. For example, let's have this map:

{:a :b
 :c {:d {:e :f
         :g :h}
     :i :j}}

This map decomposed should look like this:

[[:a :b]
 [:c {:d {:e :f
          :g :h}
      :i :j}]
 [:d {:e :f
      :g :h}]
 [:e :f]
 [:g :h]
 [:i :j]]

Order of the output does not matter.

I'm thinking about solving this with a recursive function, tree-seq, or clojure.walk. I suspect I might be missing something from the Clojure standard library. What would be the best solution to approach this?

like image 518
Jindřich Mynarz Avatar asked Apr 29 '26 06:04

Jindřich Mynarz


1 Answers

Here's a solution that uses tree-seq:

(defn decompose [m]
  (mapcat (partial tree-seq (comp map? val) val) m))

This produces a sequence of MapEntrys.

like image 72
Sam Estep Avatar answered May 02 '26 22:05

Sam Estep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!