Dropdown options from the database without duplicates in Wix

Create the options list from existing database. Remove duplicated options.

Wix Code Experts
2 min readNov 8, 2018

HIRE now

The aim is to create a dropdown with values from the collection and without duplicates. For example:

When the collection has a “Type” field duplicates :

Let’s take a look at the code:

import wixData from 'wix-data';$w.onReady(function () {  wixData.query("Example")    .find()    .then( (res) =>{    const uniqueFieldValues = getUniqueFieldValues(res.items, "type");     $w('#dropdown').options = buildOptions(uniqueFieldValues);     }, (error) => {  console.log(error);   })});function getUniqueFieldValues(items , field) {   const FieldValuesOnly = items.map(item => item[field]);   return [...new Set(fieldValuesOnly)];}function buildOptions(uniqueList) {   return uniqueList.map(value => {     return {label:value, value:value};   });}

First of all, we have to import wixData. This module allows us to work with data in collections. To import just write :

import wixData from 'wix-data';

Then, when the page is ready, build a query from your collection using wixData.query(“your_collection”) and hande the result

wixData.query("Example")  .find()  .then( (res) =>{// your code here});

Here we have 2 additional functions:

function getUniqueFieldValues(items , field) {  // get from collection only values of the field,  // specified as a second parameter and write them to the map  const fieldValuesOnly = items.map(item => item[field]);  // turn map into the set to avoid duplicates  return [...new Set(fieldValuesOnly)];}

And

function buildOptions(uniqueList) {    return uniqueList.map(value => {    // specify filed values as label and value of dropdown //options      return {label:value, value:value};    });}

Now, we can handle result, using this functions

wixData.query("Example")  .find()  .then( (res) =>{// pass items from result as a first parameter and field 
//name as second to method to get a set of unique values
const uniqueFieldValues = getUniqueFieldValues(res.items, "type");// turn this set into options for dropdown and set them $w('#dropdown').options = buildOptions(uniqueFieldValues);}, (error) => {console.log(error);})

Visit website to get help or email us: anna.doit.wix@gmail.com.

--

--