Clojure - Recursively Semi-Flatten Nested Map -


in clojure, how can turn nested map this:

(def parent {:id "parent-1"              :value "hi dude!"              :children [{:id "child-11"                          :value "how life?"                          :children [{:id "child-111"                                      :value "some value"                                      :children []}]}                         {:id "child-12"                          :value "does work?"                          :children []}]}) 

into this:

[ [{:id "parent-1", :value "hi dude!"}] [{:id "parent-1", :value "hi dude!"} {:id "child-11", :value "how life?"}] [{:id "parent-1", :value "hi dude!"} {:id "child-11", :value "how life?"} {:id "child-111", :value "some value"}] [{:id "parent-1", :value "hi dude!"} {:id "child-12", :value "does work?"}] ] 

i'm stumbling through hacky recursive attempts , brain burnt out.

what i've got far below. data right, puts data in undesired nested vectors.

how can fixed? there nice idiomatic way in clojure?

thanks.

(defn do-flatten [node parent-tree]   (let [node-res (conj parent-tree (dissoc node :children))         child-res (mapv #(do-flatten % node-res) (:children node))         end-res (if (empty? child-res) [node-res] [node-res child-res])]     end-res))  (do-flatten parent []) 

which produces:

[ [{:id "parent-1", :value "hi dude!"}]  [[ [{:id "parent-1", :value "hi dude!"} {:id "child-11", :value "how life?"}] [[ [{:id "parent-1", :value "hi dude!"} {:id "child-11", :value "how life?"} {:id "child-111", :value "some value"}] ]]] [ [{:id "parent-1", :value "hi dude!"} {:id "child-12", :value "does work?"}] ]] ] 

i don't know if idiomatic, seems work.

(defn do-flatten   ([node]    (do-flatten node []))   ([node parents]    (let [path (conj parents (dissoc node :children))]      (vec (concat [path] (mapcat #(do-flatten % path)                                  (:children node))))))) 

you can leave off [] when call it.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -