You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scss是否有类似JS Array.prototype.find()的函数?嵌套Map查找咨询

在SCSS中实现类似JavaScript的find功能查找嵌套Map对象

SCSS本身没有原生的find方法,但可以通过自定义函数快速实现需求,以下是最简方案:

1. 自定义查找函数

@function map-find($map, $match-key, $match-value) {
  @each $item in $map {
    @if map-get($item, $match-key) == $match-value {
      @return $item;
    }
  }
  @return null; // 未找到匹配项时返回null
}

2. 使用示例

基于你提供的$myMap,查找name为'a'的对象:

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

// 调用函数执行查找
$result: map-find($myMap, name, 'a');

// 调试查看结果(可选)
@debug $result;
// 输出:(name: 'a', size: (height: 100, width: 100))

说明

  • 函数map-find接收三个参数:目标嵌套Map、要匹配的键(如name)、要匹配的值(如'a')
  • 遍历Map中的每个子项,通过map-get获取子项的对应键值,匹配成功则直接返回该子项
  • 若遍历结束未找到匹配项,返回null

内容的提问来源于stack exchange,提问作者aboutjquery

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 09:42:04