SyntaxStudy
Sign Up
SASS / SCSS Merging and Manipulating Maps
SASS / SCSS Beginner 1 min read

Merging and Manipulating Maps

The `sass:map` module provides several functions for building and modifying maps programmatically. `map.merge($map1, $map2)` combines two maps into a new one, with keys from the second map overriding duplicates from the first. `map.set($map, $key, $value)` returns a new map with a single key added or updated. `map.remove($map, $keys...)` returns a new map with the specified keys removed. Because SASS maps are immutable (every operation returns a new map rather than modifying the original), you must assign the result back to the variable: `$map: map.merge($map, $overrides)`. This functional approach prevents unexpected mutation of shared maps across partials. Deep-merging nested maps requires `map.deep-merge($map1, $map2)`, which recursively merges nested map values rather than replacing them wholesale. Similarly, `map.deep-remove($map, $keys...)` navigates into nested maps to remove a specific deep key. These deep variants are particularly useful when building configurable design token systems where consumers need to override only a subset of a nested configuration.
Example
// ── map.merge — combining maps ────────────────────────────────────────────────

@use 'sass:map';

$default-spacing: (
    'xs': 0.25rem,
    'sm': 0.5rem,
    'md': 1rem,
    'lg': 1.5rem,
    'xl': 2rem
);

$extended-spacing: (
    '2xl': 3rem,
    '3xl': 4rem,
    '4xl': 6rem
);

// Merge to produce a combined map
$spacing: map.merge($default-spacing, $extended-spacing);

@each $key, $value in $spacing {
    .p-#{$key}  { padding      : $value; }
    .m-#{$key}  { margin       : $value; }
    .px-#{$key} { padding-left : $value; padding-right : $value; }
    .py-#{$key} { padding-top  : $value; padding-bottom: $value; }
}

// ── map.set — adding / updating a key ────────────────────────────────────────

$colors: (
    'primary'  : #3498db,
    'secondary': #2ecc71
);

// Returns new map with 'danger' added
$colors: map.set($colors, 'danger', #e74c3c);
$colors: map.set($colors, 'warning', #f39c12);

// ── map.remove — removing keys ────────────────────────────────────────────────

$all-tokens: (
    'debug-border' : red,
    'primary'      : #3498db,
    'secondary'    : #2ecc71,
    'debug-bg'     : pink
);

// Strip debug keys in production
$production-tokens: map.remove($all-tokens, 'debug-border', 'debug-bg');

// ── map.deep-merge for nested configuration ───────────────────────────────────

$defaults: (
    'colors': ('primary': #3498db, 'secondary': #2ecc71),
    'spacing': ('base': 1rem, 'scale': 1.5)
);

$overrides: (
    'colors': ('primary': #8e44ad)   // only override primary
);

$config: map.deep-merge($defaults, $overrides);
// Result: colors.primary = #8e44ad, colors.secondary = #2ecc71 (preserved)