Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

clojure iteratively destructure array of strings

Tags:

clojure

I'm learning clojure, and I want to take a vector of names, in last name -> first name order, of multiple people, and convert it to a vector of maps...

["Pan" "Peter" "Mouse" "Mickey"]

Should become...

[{:firstName Peter, :lastName Pan} {:firstName Mickey, :lastName Mouse}]

I've tried this, which doesn't work...

(for [[lastName firstName] 
      (list ["Pan" "Peter" "Mouse" "Mickey"])]
  {:firstName firstName, :lastName lastName}
  )

If I remove the list it turns the first/last name into individual characters.

I'm at a complete loss as to how to go about doing this.

like image 698
Trenton D. Adams Avatar asked Dec 06 '25 05:12

Trenton D. Adams


1 Answers

You can convert your input vector into a sequence of pairs with partition:

(def names ["Pan" "Peter" "Mouse" "Mickey"])
(partition 2 names)

You can convert a pair of lastName/firstName into a map using zipmap e.g.

(zipmap [:lastName :firstName] ["Pan" "Peter"])

You can convert the sequences of pairs into a sequence of maps using map:

(map #(zipmap [:lastName :firstName] %) (partition 2 names))
like image 199
Lee Avatar answered Dec 09 '25 00:12

Lee