where 筛选符合条件的元素
where 过滤器用于创建一个新的数组,其中仅包含符合特定属性值的对象。如果不指定具体的值,它默认会筛选出所有该属性值为 真值(truthy) 的对象。
在此示例中,假设您有一个产品列表,并且希望将厨房用品单独展示。使用 where,您可以创建一个仅包含 "type" 为 "kitchen" 的产品的数组。
输入
All products:
{% for product in products %}
- {{ product.title }}
{% endfor %}
{% assign kitchen_products = products | where: "type", "kitchen" %}
Kitchen products:
{% for product in kitchen_products %}
- {{ product.title }}
{% endfor %}
输出
All products:
- Vacuum
- Spatula
- Television
- Garlic press
Kitchen products:
- Spatula
- Garlic press
假设您有一个产品列表,并且只想展示可供购买的产品。您可以使用 where,仅指定属性名称而不设置目标值,以包含所有 "available" 值为 truthy 的产品。
输入
All products:
{% for product in products %}
- {{ product.title }}
{% endfor %}
{% assign available_products = products | where: "available" %}
Available products:
{% for product in available_products %}
- {{ product.title }}
{% endfor %}
输出
All products:
- Coffee mug
- Limited edition sneakers
- Boring sneakers
Available products:
- Coffee mug
- Boring sneakers
where 过滤器还可以与 first 过滤器结合使用,从数组中查找单个对象。例如,假设您想展示您新秋季系列中的一件衬衫。
输入
{% assign new_shirt = products | where: "type", "shirt" | first %}
Featured product: {{ new_shirt.title }}
输出
Featured product: Hawaiian print sweater vest