How to Sort and Filter Add-ons
Xano's add-ons feature simplifies the process of retrieving related data from reference tables, eliminating the need for multiple API requests or database functions. However, sometimes you may want to filter or sort the data returned by these add-ons. Let's explore how to accomplish this in Xano.
Filtering Add-ons
To filter add-ons, follow these steps:
Set up your database: In this example, we have a
userstable with a column referencing thecompanytable. Thecompanytable contains anamecolumn, and theproductstable has aname, a reference to thecompany, and arelease_datecolumn.Create an input: Add a text input field to your API endpoint. This input will be a list of text strings representing the product names you want to filter.
Query the main table: Use the
Query All Recordsfunction to retrieve data from your main table (e.g.,users).Separate the add-on data: Create a variable to separate the add-on data (e.g.,
company) from the main query results. This will make it easier to work with the add-on data later.Filter the add-on data:
- Create an empty array variable to store the filtered data.
- Use a
forloop to iterate through the separated add-on data. - Within the loop, use the
Array Find All Elementsfunction to filter the add-on data based on the input text strings (e.g., filterproductswhere thenameis in the input list). - Update the filtered data array with the filtered add-on data.
- Filter the main data:
- Create an empty array variable to store the filtered main data.
- Use a
forloop to iterate through the main data. - Within the loop, use the
Array Find First Elementfunction to match the filtered add-on data with the corresponding main data (e.g., match thecompanywith theuserbased on thecompany_idfield). - Update the filtered main data array with the matched data and filtered add-on data.
- Return the filtered data: Return the filtered main data array, which now includes the filtered add-on data.
Sorting Add-ons
Sorting add-ons is a simpler process than filtering, thanks to Xano's XenoTransform feature. Here's how you can sort add-ons:
Create a variable: Create a variable and assign it the value returned from your main query (e.g.,
users).Use the
Set Filterfunction: Within theSet Filterfunction, define the path to the add-on data you want to sort (e.g.,_products.of_company).Apply the sorting expression:
- To sort by name, use the expression
$$_products.of_company|sort('name'). - To sort by release date, first convert the date field to a numeric timestamp using
$$_products.of_company|map(x=>x.release_date=Date.parse(x.release_date)), then sort by therelease_datefield:|sort('release_date').
- Return the sorted data: Return the variable containing the sorted add-on data.
By following these steps, you can effectively filter and sort add-ons in Xano, ensuring that you retrieve the desired data in the preferred order.
Sign up for Xano.
100,000+ people build on Xano.
Start today and scale to millions.