leontalbot
leontalbot

Reputation: 2543

Duplicate map in collection based on value in specific key

So I have this:

[{:a ["x" "y"], :b "foo"}
 {:a ["x" "y" "z"], :b "bar"}]

And want this:

[{:a "x", :b "foo"} 
 {:a "y", :b "foo"} 
 {:a "x", :b "bar"}
 {:a "y", :b "bar"}
 {:a "z", :b "bar"}]

How can I do this?

Upvotes: 1

Views: 115

Answers (2)

Lee
Lee

Reputation: 144136

You can use mapcat:

(def c [{:a ["x" "y"], :b "foo"}
        {:a ["x" "y" "z"], :b "bar"}])

(mapcat (fn [{:keys [a] :as m}] (map #(assoc m :a %) a)) c)

Upvotes: 3

cfrick
cfrick

Reputation: 37008

for is really nice for known levels of nesting:

(for [x [{:a ["x" "y"], :b "foo"}
         {:a ["x" "y" "z"], :b "bar"}]
      a (:a x)] 
  (assoc x :a a))

Upvotes: 5

Related Questions