How to use map-deep-get in sass

Viewed 2468

I was following this article https://www.sitepoint.com/better-solution-managing-z-index-sass/ But there is a missing link where it doesn't link the map-deep-get function back into the z function, and the demo doesn't work. I've tried searching but found no help.

$z-layers: (
  "goku":            9001, 
  "shoryuken":       8000,
  "modal": (
    "base":           500,
    "close":          100,
    "header":          50,
    "footer":          10
  ),
  "default":            1,
  "below":             -1,
  "bottomless-pit": -9000
);

@function map-deep-get($map, $keys...) {
  @each $key in $keys {
    $map: map-get($map, $key);
  }

  @return $map;
}

@function z($layer) {
  @if not map-has-key($z-layers, $layer) {
    @warn "No layer found for `#{$layer}` in $z-layers map. Property omitted.";
  }

  @return map-get($z-layers, $layer);
}


2 Answers

Map-deep-get


Syntax

Dart Sass syntax:

@use "sass:list";
@use "sass:map";
@use "sass:meta";

@function map-deep-get($map, $keys...) {
   $scope: $map; $i: 1;
   @while (meta.type-of($scope) == map) and ($i <= list.length($keys)) {
      $scope: map.get($scope, list.nth($keys, $i));
      $i: $i + 1;
   }
   @return $scope;
}

Lib Sass syntax:

@function map-deep-get($map, $keys...) {
   $scope: $map; $i: 1;
   @while (type-of($scope) == map) and ($i <= length($keys)) {
      $scope: map-get($scope, nth($keys, $i));
      $i: $i + 1;
   }
   @return $scope;
}

How to use:

This map-deep-get function let's you acces as deeply nested values as you want and can also be used as a regular map-get function.

$exampleMap: (
   "foo": foo,
   "bar": (
      "barfoo": barfoo,
      "barbar": (
         "barbarfoo": barbarfoo,
      ),
   ),
);

Codepen Demo

Not nested item:

@debug map-deep-get($exampleMap, "foo") //foo

Nested item:

@debug map-deep-get($exampleMap, "bar", "barfoo") //barfoo

Nested map:

@debug map-deep-get($exampleMap, "bar", "barbar") //("barbarfoo": barbarfoo)

Nested nested item:

@debug map-deep-get($exampleMap, "bar", "barbar", "barbarfoo") //barbarfoo
Related