Skip to content

Instantly share code, notes, and snippets.

@pascalduez
Last active September 22, 2022 08:05
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pascalduez/14ef79d644483fc262da to your computer and use it in GitHub Desktop.
Save pascalduez/14ef79d644483fc262da to your computer and use it in GitHub Desktop.
Deep nested values in Sass maps
// ----
// Sass (v3.3.7)
// Compass (v1.0.0.alpha.18)
// ----
// Deep nested values in Sass maps.
// Fetch a deep value in a multi-level map.
// https://gist.github.com/KittyGiraudel/9933331
@function map-fetch($map, $keys) {
@each $key in $keys {
$map: map-get($map, $key);
}
@return $map;
}
// Set or update a deep nested value in map.
@function map-set($map, $keys, $new) {
$orig: $map;
$cache: ();
$length: length($keys);
$last: nth($keys, $length);
@each $key in $keys {
$map: map-get($map, $key);
@if $key == $last {
$map: map-merge($map, $new);
}
$cache: append($cache, $map);
}
$i: $length;
@while $i > 1 {
$prev: $i - 1;
$cache: set-nth($cache, $prev, map-merge(
nth($cache, $prev),
(nth($keys, $i): nth($cache, $i))
));
$i: $prev;
}
@return map-merge($orig, (nth($keys, 1): nth($cache, 1)));
}
// Test
Sass {
$map: (
one: (
val: 1,
two: (
val: 2,
three: (
val: 3,
four: (
val: 4
)
)
)
),
foo: "foo",
bar: "bar"
);
$flag: "flag!";
/* It should append a new value */
$test: map-set($map, one two three four, (test: $flag));
test: inspect($test);
test: map-fetch($test, one two three four test) == $flag;
/* It should update a defined value */
$test: map-set($map, one two three four, (val: $flag));
test: inspect($test);
test: map-fetch($test, one two three four val) == $flag;
}
Sass {
/* It should append a new value */
test: (one: ((val: 1, two: ((val: 2, three: ((val: 3, four: ((val: 4, test: "flag!")))))))), foo: "foo", bar: "bar");
test: true;
/* It should update a defined value */
test: (one: ((val: 1, two: ((val: 2, three: ((val: 3, four: ((val: "flag!")))))))), foo: "foo", bar: "bar");
test: true;
}
@kamescg
Copy link

kamescg commented Feb 7, 2015

Thank you - what a great little snippet 😄

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment