skip to Main Content

In Retool I am trying to have the input of one box determine the dispalyed options of a second input box, i.e if you select district one in the "district" box (Districtbox) then it will only display projects A, B and C as selectable options in the "project" box. This is my JS code but the resultingProject returns an empty output even if const inputDistrict = 'One' or const inputDistrict = Districtbox.value

  // Given project and district pairs
const projectDistrictPairs = [
  { project: 'A', district: 'One' },
  { project: 'B', district: 'One' },
  { project: 'C', district: 'One' },
  { project: 'D', district: 'Two' },
  { project: 'E', district: 'Three' },
  { project: 'F', district: 'Four' }
];

// Assuming you have an input variable named 'inputDistrict' that holds the input district value
const inputDistrict = 'One';

// Find the resulting project for the selected district
const resultingProject = projectDistrictPairs.find(pair => pair.district === inputDistrict)?.project;

console.log(resultingProject);

2

Answers


  1. This is my JS code but the resultingProject returns an empty output even if const inputDistrict = ‘One’

    No, your code returns A as a result.

    As the find() method returns the first element in the provided array that satisfies the provided testing function, you can use reduce to filter out all the matching projects

    // Given project and district pairs
    const projectDistrictPairs = [
      { project: 'A', district: 'One' },
      { project: 'B', district: 'One' },
      { project: 'C', district: 'One' },
      { project: 'D', district: 'Two' },
      { project: 'E', district: 'Three' },
      { project: 'F', district: 'Four' }
    ];
    
    // Assuming you have an input variable named 'inputDistrict' that holds the input district value
    const inputDistrict = 'One';
    
    // Use reduce to filter out the matchings
    const resultingProject = projectDistrictPairs.reduce((accumulator, currentPair) => {
      if (currentPair.district === inputDistrict) {
        accumulator.push(currentPair.project);
      }
      return accumulator;
    }, []);
    
    console.log(resultingProject);
    Login or Signup to reply.
  2. You can use filter to filter out projects.
    
    `const inputDistrict = 'One';`
    
    `const resultingProject = projectDistrictPairs.filter(pair => pair.district === inputDistrict);`
    
    This will return the array of JSON
    
    `[
      { project: 'A', district: 'One' },
      { project: 'B', district: 'One' },
      { project: 'C', district: 'One' }
    ]`
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search