THX1137
THX1137

Reputation: 973

How do I return two elements from a map function in the following code?

This is a follow on for another question I asked here for which I got an awesome answer. The premise is slightly modified from that question to allow this one.

How do I generate a table row with :td's for both 'name' and 'value' as shown in this data structure:

(table-rows [{:name "foo" :value 1} {:name "hey" :value 2}])

starting with

(defn table-rows [data]
  (->> data
       (map (fn [{:keys [name] :as row}]
              [:td (:name row)]))
       (into [:tr])))

which returns at this point

=> [:tr [:td "foo"] [:td "hey"]]

The map (fn...) will only return the last element, right? And if I enclose the two [:td]'s in something, so that it is returned as a unit, the table would not work.

In my project I will have many more [:td...] elements than two; I chose two to simplify my question.

I suspect let is what I should be considering, but every time I start down that road I run into trouble so I thought I would ask.

UPDATE:

One question in the comments allowed me to realize this is what I'm looking for:

  (->> data
       (map (fn [{:keys [name] :as row}]
              [:tr
               [:td (:name row)]
               [:td (:value row)]]))
       (into [:tbody])))

which produces what I was after:

[:tbody [:tr [:td "foo"] [:td 1]] 
        [:tr [:td "hey"] [:td 2]]]

Thank you for the help!

UPDATE 2:

and I realize I can remove the destructuring from the argument to the 'fn' so that I have:

(defn table-rows [data]
  (->> data
       (map (fn [row]
              [:tr
               [:td (:name row)]
               [:td (:value row)]]))
       (into [:tbody])))

Upvotes: 1

Views: 74

Answers (1)

THX1137
THX1137

Reputation: 973

Thanks to some wonderful help in the comments below, I was able to work out what I needed, which is:

(defn table-rows [data]
  (->> data
       (map (fn [row]
              [:tr
               [:td (:name row)]
               [:td (:value row)]]))
       (into [:tbody])))

which produces

[:tbody [:tr [:td "foo"] [:td 1]] 
        [:tr [:td "hey"] [:td 2]]]

Thanks you for the help!

(note to self: make sure to work out what I am trying to get from a function before posting here)

PS - it looks like I have to wait a few days to accept my own answer, which it was suggested I do so that this doesn't appear unanswered.

Upvotes: 2

Related Questions