Filtering options in a select depending of the value of an other select value

Hello all,

Im reading the forum for a while without collaborating that much. After I read other helpful thread this morning I decide to collaborate too.

First of all I want to say that the answer of this can be : You've been rocked too close from the wall, there is a 10x better way to accomplish this, just read the docs.

I have two select : One for selecting the category and a other other one to select the subcategory of a product. The second select is disabled until the first one get an option selected. After that I obviously want to filter the options of the second select and do not provide all of the subcategory but only the subcategory matching the category selected.

Here is my method without re-quering my SQL database :

I use a transformer like this :

// I try here to populate the sub category using js and not sql

let catData = {{AUR_getCategory.data}} //This is the result of my SQL query returning all the category and subcategory
let newCatData = {}
let indexToRemove = [];

// Get the index of the value we want to remove from the array
for(const key in catData){
  const currentArray = catData[key];
  if (key == "PSu_category"){
    for (let i = 0; i < currentArray.length; i++){
      if(currentArray[i] != {{ select3.value }}){
        indexToRemove.push(i)
      }
    }
  }
}
// Sort the indices in descending order to avoid index shifting when splice
indexToRemove.sort((a, b) => b - a);
//Remove the value at the corresponding array and rebuild the object to return as a result of the transformer
for(const key in catData){
  const currentArray = catData[key];
  indexToRemove.forEach(value => {
    currentArray.splice(value, 1);
  })
  newCatData[key] = currentArray;
}

return newCatData;

Did I miss something ? Should I ask my parent if they rocked me to close from the wall 25 years ago ?

Thanks a lot,

RP

Hey Robert!

  1. Definitely rocked very far away from any walls :wink:
  2. Without looking too closely, your approach looks good to me.
  3. Looking a bit closer, is there a reason you're removing instead of just filtering?

let newCatData = {};

for (const key in catData) {

const currentArray = catData[key];

newCatData[key] = currentArray.filter(item => item === {{ select3.value }});

}

Also, is there a case in which ({{ select3.value }}) is not found in the array?

How is your code currently working? Any specific errors?

Talk soon! :wave:

1 Like

Hi Victoria,
Thanks for your answer.

There is absolutely no reason for removing when I can filter. The select3.value must exist at that level it was required field.

Have a great day,

RP