Merge multiple Sass maps

五迷三道 提交于 2020-01-11 04:04:17

问题


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);

回答1:


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);



回答2:


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.




回答3:


Note: Starting with Dart Sass 1.23.0, merge will be available via the map module.

@use "sass:map";

$light-weights: ("lightest": 100, "light": 300);
$heavy-weights: ("medium": 500, "bold": 700);

@debug map.merge($light-weights, $heavy-weights);
// (
//   "lightest": 100,
//   "light": 300,
//   "medium": 500,
//   "bold": 700
// )

// map.merge() can be used to add a single key/value pair to a map.
@debug map.merge($light-weights, ("lighter": 200));
// ("lightest": 100, "light": 300, "lighter": 200)

// It can also be used to overwrite a value in a map.
@debug map.merge($light-weights, ("light": 200));
// ("lightest": 100, "light": 200)

See documentation for more examples: https://sass-lang.com/documentation/modules/map



来源:https://stackoverflow.com/questions/27740063/merge-multiple-sass-maps

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!