Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge multiple Sass maps

Tags:

merge

sass

maps

I have three Sass maps that I want to merge into one map. With the map-merge function I can only merge two maps together. How can I merge more than two maps?

A shortened example of my situation:

    $color-name: (
        blue: (
            default: blue,
            dark: navy,
            light: sky
        )
    );

    $color-event: (
        danger: (
            default: set($color-name, red),
            dark: set($color-name, red, dark),
            light: set($color-name, red, light),
        )
    );

    $color-category: (
        heading: (
            default: set($color-name, grey),
            dark: set($color-name, grey, dark),
            light: set($color-name, grey, light)
        )
    );

    $color: map-merge($color-name, $color-event, $color-category);
like image 276
Ben Besuijen Avatar asked Jan 02 '15 09:01

Ben Besuijen


People also ask

How do I merge arrays in maps?

To merge Maps, use the spread operator (...) to unpack the values of two or more Maps into an array and pass them into the Map() constructor, e.g. new Map([... map1, ... map2]) . The new Map will contain the key-value pairs from all provided Map objects.

Which map function returns all keys in a map in Sass?

map-keys($map) function: This function returns the list of the keys in the given map.

What is a SCSS map?

Maps in Sass hold pairs of keys and values, and make it easy to look up a value by its corresponding key. They're written (<expression>: <expression>, <expression>: <expression>) . The expression before the : is the key, and the expression after is the value associated with that key.


2 Answers

I realize this is a bit late, but since this was the only solution I could find while googling I want to post this for others looking for a similar solution.

I stumbled upon this question trying to find the same answer, and while @cimmanon's answer may work for your specific example of combining only 3 maps, it isn't a good solution if you wanted to combine, say 10 maps. I wanted a solution that could be applied to 3 maps or 50. So I wrote a function to handle merging multiple maps together:

@function map-collect($maps...) {
  $collection: ();

  @each $map in $maps {
    $collection: map-merge($collection, $map);
  }
  @return $collection;
}

And use it like so:

$colors: map-collect($color-name, $color-event, $color-category); 

Since this uses the map-merge function, SASS 3.3+ is required.

like image 188
biggles Avatar answered Sep 18 '22 19:09

biggles


If map-merge takes 2 mappings and returns a single mapping, but you have 3 mappings... you use map-merge twice.

$color: map-merge(map-merge($color-name, $color-event), $color-category);
like image 29
cimmanon Avatar answered Sep 20 '22 19:09

cimmanon