Originally published at: http://www.sitepoint.com/extra-map-functions-sass/
Sass maps are awesome. They make a lot of things that were previously impossible, well, possible. For instance, they have a smart way to define dynamic variables. They are also the perfect container for a complex configuration, for a framework or a grid system.
Fortunately for us, Sass provides a handful of functions to manipulate maps. Yet, if you keep working with Sass you might come up with an edge case that is not being covered by the built-in API.
Perhaps you’ll need a way to get a key that is being nested within several maps? What if you want to update this key? Or extend nested maps like $.extend
from jQuery? A few problems here and there that can be easily fixed with the functions we’ll inspect today.
Map Deep Get
When you need to access a key that belongs to a map which happens to be nested within another map (or several), you cannot rely on map-get
anymore. At least, not as it currently is.
/// Fetch nested keys /// @param {Map} $map - Map /// @param {Arglist} $keys - Keys to fetch /// @return {*} @function map-deep-get($map, $keys...) { @each $key in $keys { $map: map-get($map, $key); } @return $map; }
Example
$grid-configuration: ( 'columns': 12, 'layouts': ( 'small': 800px, 'medium': 1000px, 'large': 1200px, ), ); // Without `map-deep-get` $medium: map-get(map-get($grid-configuration, 'layouts'), 'medium'); // With `map-deep-get` $medium: map-deep-get($grid-configuration, 'layouts', 'medium');
Map Deep Set
As you can see, building a function to get a key from within nested maps is not overly difficult to write. On the other hand, a function to set a value at the end of a key chain is not as easy to build… Because of the complexity, we will not get too deep into the code for this one.
Continue reading this article on SitePoint