where¶
The 'where' filter is designed to select elements from an array that match a specific condition based on a property value. It functions similarly to a "filter" or "where" clause in SQL or other query languages.
Functionality
- Arrays of Objects: Takes an array of objects as input.
- Property and Value: Requires a property name (string) and a target value to filter by.
- Matching: Evaluates each object in the array, keeping only those where the specified property matches the target value.
- Output: Returns a new array containing only the objects that satisfied the condition.
Syntax
Arguments- property_name: A string representing the name of the property to check for each object.
- target_value: The value that the specified property should match for an object to be included in the result.
Code Samples
Example 1: Filtering by a String Property
{% assign products = [{ "name": "Product A", "category": "Electronics" },
{ "name": "Product B", "category": "Clothing" },
{ "name": "Product C", "category": "Electronics" }] %}
{{ products | where: "category", "Electronics" }}
Output:
Example 2: Filtering by a Number Property {% assign users = [{ "name": "Alice", "age": 30 },
{ "name": "Bob", "age": 25 },
{ "name": "Charlie", "age": 35 }] %}
{{ users | where: "age", 30 }}
Output:
Example 3: Filtering with Boolean Values (Implicit True) {% assign tasks = [{ "name": "Task 1", "completed": true },
{ "name": "Task 2", "completed": false },
{ "name": "Task 3", "completed": true }] %}
{{ tasks | where: "completed" }}
Outliers and Special Cases¶
- Empty Arrays: If the input array is empty, the
wherefilter returns an empty array. - Non-Array Input: If the input is not an array of objects, the
wherefilter returns the original input value unchanged. - Invalid Property: If the specified
property_namedoes not exist on the objects, the filter may return an error or unexpected results (depending on Experience Builder's error handling). - Type Coercion: Be mindful of data types when specifying the
target_value. Experience Builder might perform type coercion if the types don't match exactly (e.g., comparing a string "30" with a number 30 might still be considered a match).
Key Points¶
- The
wherefilter is a powerful tool for filtering and extracting specific subsets of data from arrays of objects. - It allows you to create dynamic and conditional content based on object properties.
- Pay attention to data types to ensure accurate filtering.
- Consider using the
mapfilter in conjunction withwherefor more complex filtering scenarios.