clojurescript - Convert vector of maps to a tree -
i need convert vector of maps this:
[{:id 1 :parent nil :name "a"} {:id 2 :parent 1 :name "b"} {:id 3 :parent 2 :name "c"} {:id 4 :parent 2 :name "d"} {:id 5 :parent 4 :name "e"}]
to this:
[{:id 1 :parent nil :name "a" :nodes [{:id 2 :parent 1 :name "b" :nodes [{:id 3 :parent 2 :name "c"} {:id 4 :parent 2 :name "d" :nodes [{:id 5 :parent 4 :name "e"}]}]}]}]
update:
as per requested far have this:
(defn enum [s] (map vector (range) s)) (defn build-tree [tree current-path current-parent gr] (if-let [nodes (gr current-parent)] (let [current-path (conj current-path :nodes) new-tree (assoc-in tree current-path nodes)] (first (for [[i node] (enum (get-in new-tree current-path))] (build-tree new-tree (conj current-path i) (:id node) gr)))) tree)) (defn list->tree [ls] (let [gr (group-by :parent ls) root (first (gr nil))] (build-tree root [] (:id root) gr)))
however doubt idiomatic + not working anyway (creates first nodes, rest ignored). doubt creating tree hard. think missing something.
you can either use adjacency list or recursive approach.
both approaches discussed in more detail answers to similar question.
Comments
Post a Comment