sassnestednested-listssass-maps

SCSS/SASS get values from nth nested maps


I'm having trouble trying to retrieve values within nested sass maps. I have a map that looks like this:

$breakpoints : (
    xl: (
         page-width: 1170px,
         gutter: 30px,
         base-font-size: 17px
    ),
    l: (
         breakpoint: 1170px,
         page-width: 980px,
         gutter: 20px,
         base-font-size: 17px
    )
);

I am trying to retrieve variables within the first nested list "xl". The idea is to retrieve the nested list by index and not by the key name as this should be able to by modified to the user's liking.

I would have thought that using map-get(nth($breakpoints, 1), page-width) would have worked but nth($breakpoints, 1) seems to return a string containing "xl (page-width: 1170px, gutter: 30px, base-font-size: 17px)" rather than an actual map and is therefor unusable with the map-get() function.

Any ideas on how to do this?


Solution

  • You can create a function that converts numeric indexes to string keys:

    @function index-to-key($index) {
      $keys: map-keys($breakpoints); // A list of all keys in a $breakpoints map
    
      @return nth($keys, $index);
    }
    

    Then call this function:

    width: map-get(map-get($breakpoints, index-to-key(1)), page-width);
    

    Where inner map-get returns the map xl from $breakpoints and outer map-get returns value by key page-width.


    Full code on Sassmeister.
    map-keys function description.