Scan selector
Learn how to collect values from nested structures.
The scan selector allows you to scan and retrieve values from nested data structures. It recursively iterates through the data structure and returns a list of all corresponding values.
For example, let's say you have the following data structure representing an e-commerce store's inventory:
let inventory = [["category": "📱 Electronics","items": [["name": "Smartphone", "price": 500],["name": "Tablet", "price": 400],]],["category": "👗 Fashion","items": [["name": "T-shirt", "price": 25],["name": "Jeans", "price": 60],],],["category": "🍳 Home & Kitchen","items": [["name": "Toaster", "price": 30],["name": "Blender", "price": 75]],],];
Using the scan selector, you easily find the cheapest item in the inventory:
min of inventory[...].price
Here, the scan selector iterates through the inventory and creates a list of all the prices. Then, the min macro returns the lowest price in the list, which is $25.
You can use the same idea to check whether the user has added an Apple product to their cart:
some brand in cart[...].brand satisfies brand is "Apple"
This time, the scan selector iterates through the cart and creates a list of all the brands. Then, the some quantifier checks if Apple is in the list.
The scan selector also supports an optional maximum depth parameter, which allows you to limit the depth of the search and potentially speed up the query.
For example, let's update the inventory to include subcategories and see how this works:
let inventory = [ // Level 1[ // Level 2"category": "📱 Electronics","items": [ // Level 3["name": "Desktop computer", "price": 900], // Level 4],"subcategories": [["category": "🎮 Gaming","items": [["name": "Gaming console", "price": 500],["name": "Gaming headset", "price": 100]],],],],];
Now, let's say you want to sum the prices, but only for the root categories. You can use the scan selector with a maximum depth of 4 to achieve this:
sum of inventory[...4].price
Since the desktop computer is the only item in a root category, the result is $900 instead of $2500.