简体   繁体   中英

Converting vector to indexed map in Clojure?

Let's say I have the following vector of maps:

[{:name "Jack" :age 5}
{:name "Joe" :age 15}
{:name "Mare" :age 34}
{:name "William" :age 64}
{:name "Adolf" :age 34}]

I want to convert this to an indexed map, like:

{1 {:name "Jack" :age 5}
 2 {:name "Joe" :age 15}
 3 {:name "Mare" :age 34}
 4 {:name "William" :age 64}
 5 {:name "Adolf" :age 34}}

And at some point, when I have modified the indexed map, I want to convert it back to vector of maps.

How to do it?

You can use map-indexed in order to associate each map to its index and then reduce it into an hashmap: (reduce into {} (map-indexed #(assoc {} %1 %2) test))

If you want to go back to your first structure: (vec (vals your-indexed-map))

zipmap combines a series of keys and values, so you could do:

(zipmap (iterate inc 1) data-vector)

(with data-vector being your vector of maps)

The reverse would basically be sorting by key, then taking all values, which can be written exactly like that:

(->> data-map
     (sort-by key)
     (map val))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM