This code queries an "Admin" collection in Wix's data, extracts unique values from the "firstName" field of the retrieved items, and populates a dropdown element with these unique values as options. Error handling is also included to handle and log any query errors.
// Query the "Admin" collection in Wix's data
wixData.query("Admin")
.find()
.then((res) => {
// Extract unique values from the "firstName" field of the retrieved items
const uniqueFieldValues = getUniqueFieldValues(res.items, "firstName");
// Populate a dropdown element with the unique values as options
$w('#dropdown1').options = buildOptions(uniqueFieldValues);
}, (error) => {
// Handle and log any errors that occur during the query
console.log(error);
});
// Function to extract unique values from an array of items based on a specified field
function getUniqueFieldValues(items, field) {
// Extract the values of the specified field from the items
const fieldValuesOnly = items.map(item => item[field]);
// Use a Set to ensure only unique values are retained, and then convert it back to an array
return [...new Set(fieldValuesOnly)];
}
// Function to format unique values as options for a dropdown element
function buildOptions(uniqueList) {
// Create options with labels and values from the unique values list
return uniqueList.map(value => {
return { label: value, value: value };
});
}