27

I have the following data structure:

{:file #<File /foo.bar>, :resolution {:width 1280, :height 1024}}

I would like to write a function that destructures the :resolution key into width and height symbols. Something like

(defn to-directory-name [{{:keys [width height]}} wallpaper]
  (str width "x" height))

Is something like that possible with destructuring?

Thanks.

Tim Visher
  • 12,786
  • 16
  • 58
  • 66

2 Answers2

30

You must first destructure :resolution, then get width and height:

{{:keys [width height]} :resolution}
Arjan
  • 19,957
  • 2
  • 55
  • 48
  • How can I destructure from within two different nested keys of the same map? e.g. `{{:keys [a b]} :query-params}` and `{{:keys [c d]} :path-params}` simultaneously, from the same request map – Dustin Getz Jan 07 '15 at 17:09
  • 6
    Just put them in the same `{}`: `{{:keys [a b]} :query-params {:keys [c d]} :path-params}` – Arjan Jan 07 '15 at 17:22
  • in case `:resolution` contains a much larger data structure, is there a way to destructre `width` and `height` and *still* make resolution referencable? i.e. after destructre being able to still access resolution keys like so - `(keys resolution)`? – Viktor Karsakov Nov 29 '22 at 11:36
  • `{{:keys [width height]} :resolution :as option-map` or you can use within {:keys ....} if you only need ref to resolution. – Sergey Shvets May 30 '23 at 17:39
6
(defn to-directory-name [{{width :width height :height} :resolution}] 
  (str width "x" height))

Works for me.

Maurits Rijk
  • 9,789
  • 2
  • 36
  • 53