Skip to content
Tutorials Center
My learning

Topics

Lesson 14 of 36 ยท Data Structures

Working with Nested Data in Clojure

Read and update deeply nested maps and vectors with get-in, assoc-in, update-in and dissoc, reshape data with mapv and into, and model a realistic order with nested structures.

Real data is rarely flat. A customer has an address, an order has a list of line items, each with a product. Clojure represents all of this with maps and vectors nested inside each other, and gives you a small set of functions that reach into any depth. Since the data is immutable, every "update" returns a new structure that shares the parts you did not touch.

A sample structure

Here is an order, written as plain data. It will be used in the examples below.

CLOJURE
(def order
  {:id 1001
   :customer {:name "Ada"
              :address {:city "London" :country "UK"}}
   :items [{:sku "A1" :qty 2 :price 9.5}
           {:sku "B2" :qty 1 :price 20.0}]
   :status :new})

Reading deep values: get-in

get-in takes a map and a path (a vector of keys and indexes). It returns nil (or a default) if any step is missing instead of throwing:

CLOJURE
(get-in order [:customer :name])              ; "Ada"
(get-in order [:customer :address :city])     ; "London"
(get-in order [:items 0 :sku])                ; "A1"
(get-in order [:items 5 :sku])                ; nil
(get-in order [:customer :phone] "unknown")   ; "unknown"

Vectors take numeric indexes in the path, because a vector is a function from index to element.

Replacing values: assoc-in

assoc-in sets a value at a path and creates missing maps along the way:

CLOJURE
(assoc-in order [:customer :address :city] "Paris")
(assoc-in order [:items 1 :qty] 3)
(assoc-in {} [:a :b :c] 1)      ; {:a {:b {:c 1}}}

The result is a new order; order itself is untouched. Only the maps along the path are copied. The unchanged branches, such as the other item, are shared with the original.

Applying a function: update-in

update-in is assoc-in for "new value depends on the old one". It takes a path, a function and extra arguments:

CLOJURE
(update-in order [:items 0 :qty] + 5)          ; qty 2 -> 7
(update-in order [:customer :name] str/upper-case)
(update-in order [:status] (constantly :paid))
(update order :status (constantly :shipped))   ; update works for one key

Since Clojure 1.7 there is also update for a single key, shown on the last line. update-in with inc is the usual counter:

CLOJURE
(update-in {:stats {:views 10}} [:stats :views] inc)   ; {:stats {:views 11}}

Removing nested keys

There is no dissoc-in in the core library. Combine update-in and dissoc on the parent map:

CLOJURE
(update-in order [:customer :address] dissoc :country)

This updates the address map by calling dissoc on it with :country.

JS Stand-in: get-in, assoc-in and update-in

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Changing every element: mapv and update-vals

To apply a change to each item in a nested vector, map (or mapv) over it and rebuild with assoc:

CLOJURE
(defn apply-discount [item]
  (update item :price * 0.9))

(update order :items #(mapv apply-discount %))

mapv keeps the vector type. For a map of maps, use update-vals:

CLOJURE
(update-vals {:a {:n 1} :b {:n 2}} #(update % :n inc))
;; => {:a {:n 2}, :b {:n 3}}

Computing from nested data

Reading nested data into a result is plain sequence processing. The total of the order is a reduce or a map plus apply +:

CLOJURE
(defn line-total [{:keys [qty price]}]
  (* qty price))

(defn order-total [order]
  (->> (:items order)
       (map line-total)
       (reduce +)))

(order-total order)   ; 39.0

Here line-total uses map destructuring in its parameter list (more in the Destructuring lesson), and ->> threads the items through each step (see Composition and Threading Macros).

JS Stand-in: totals and a discount across nested items

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Flattening and reshaping

Two common reshaping jobs:

CLOJURE
;; All SKUs as a flat vector
(mapv :sku (:items order))                      ; ["A1" "B2"]

;; Index the items by SKU
(into {} (map (juxt :sku identity)) (:items order))
;; => {"A1" {...}, "B2" {...}}

;; Join nested vectors into one
(apply concat [[1 2] [3] [4 5]])                ; (1 2 3 4 5)
(mapcat :tags [{:tags [:a :b]} {:tags [:c]}])   ; (:a :b :c)

(juxt :sku identity) builds a function returning a pair [sku item], so into {} turns the pairs into a map. The two-argument form (into {} xf coll) uses a transducer (a reusable transformation) and avoids creating the intermediate sequence.

If you have deeply nested data that you read and write in many places, wrap the paths in small named functions such as (defn city [order] (get-in order [:customer :address :city])). When the shape of the data changes, only those functions change.

Common mistakes

  • Putting a keyword where an index belongs (or the reverse) in a path: [:items :0] is wrong, use [:items 0].
  • Using assoc-in on a vector with an index beyond its length plus one. Appending is allowed only at exactly (count v).
  • Expecting get-in to throw on a missing step. It returns nil.
  • Forgetting that update-in hands the old value to your function as its first argument.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does (get-in {:a {:b 1}} [:a :c] :none) return?

    The path is missing, so get-in returns the default :none.
  2. 2. Which call sets the :city inside {:address {:city "X"}} to "Y"?

    assoc-in takes a map, a path vector and the new value.
  3. 3. What is (update-in {:n {:count 1}} [:n :count] inc)?

    update-in applies inc to the value at the path and returns the updated outer map.
  4. 4. Is the original map changed after assoc-in or update-in?

    All updates are persistent: the original stays intact.

Summary

  • Use get-in to read deep values safely, assoc-in to set them and update-in to transform them.
  • There is no dissoc-in; use (update-in m path dissoc k).
  • mapv and update-vals apply changes across nested collections; juxt and into reshape data.
  • Wrap common paths in named functions so a data-shape change touches one place.
  • Immutability means each update returns a new structure that shares everything it did not change.

Next: Defining Functions- heading: Path functions cards: - icon: "๐Ÿ”" title: get-in text: Read at a path. - icon: "โœ๏ธ" title: assoc-in text: Set at a path. - icon: "๐Ÿ”ง" title: update-in text: Transform at a path. note: All of them return new data.