Search code examples
sass

Does scss have a function similar to js Array.prototype.find()?


I have a nest map and want to use a value to find the object and return an object

js-like function find

const myMap = [
 { name: "a", size: {height: 100, width: 100} },
 { name: "b", size: {height: 200, width: 200} },
];

const result = myMap.find(({ name }) => name === "a");
// { name: "a", size: {height: 100, width: 100} }

My map is like this

$myMap: (
 (
 name: 'a',
 size: (
 height: 100,
 width: 100,
 )
 ),
 (
 name: 'b',
 size: (
 height: 200,
 width: 200,
 )
 )
) !default;

Is there any good method? The simpler, the better, thank you


Solution

  • I don't think there is a built-in function for this. I wrote one though and tried to keep it as basic as possible.

    @function find($name) {
      @each $map in $myMap {
        @if $name == map.get($map, "name") {
          @return $map
        }
      }
      @return null;
    }