matiasmasca
matiasmasca

Reputation: 621

Clojure how to mix/merge two maps

I'm new in clojure and I need mix a very complex (for me) maps that have inside a Vector to mix up.

Orginal map:

{:cars   {:previous-page nil, :next-page 2, :count 33, :items [{:id 1, :name "test1"}, {:id 2, :name "test2"}]},
 :trucks {:previous-page nil, :next-page 2, :count 11, :items [{:id 1, :name "test3"}, {:id 2, :name "test4"}]},
 :boats  {:previous-page nil, :next-page 2, :count 22, :items [{:id 1, :name "test5"}, {:id 2, :name "test6"}]}}

Second map:

 {:cars   {:previous-page 2, :next-page 3, :count 33, :items [{:id 3, :name "test7"}, {:id 4, :name "test8"}]},
  :trucks {:previous-page 3, :next-page 4, :count 11, :items [{:id 3, :name "test9"}, {:id 4, :name "test10"}]},
  :boats  {:previous-page 4, :next-page 5, :count 22, :items [{:id 3, :name "test11"}, {:id 4, :name "test12"}]}}

I need to mix this two maps in only one:

{:cars   {:previous-page 2, :next-page 3, :count 33, :items [{:id 1, :name "test1"}, {:id 2, :name "test2"},{:id 3, :name "test7"}, {:id 4, :name "test8"}]},
 :trucks {:previous-page 3, :next-page 4, :count 11, :items [{:id 1, :name "test3"}, {:id 2, :name "test4"},{:id 3, :name "test9"}, {:id 4, :name "test10"}]},
 :boats  {:previous-page 4, :next-page 5, :count 22, :items [{:id 1, :name "test5"}, {:id 2, :name "test6"},{:id 3, :name "test11"}, {:id 4, :name "test12"}]}} 

Upvotes: 2

Views: 466

Answers (1)

Alex Miller
Alex Miller

Reputation: 70201

You can use merge-with to combine maps with an arbitrary function. Here there does not seem to be one "rule" though - for :previous-page, :next-page, and :count seem to be "last one wins" but :items seems to be something like#(into [] %)`. Once you can state that rule clearly as a function:

(fn combine [map1 map2] ...)

You can then easily combine the maps with merge-with using whatever combine you've defined.

Upvotes: 3

Related Questions