0

I have an express endpoint, I need to get the query pass from the frontend

const { filterType1, filterType2 } = req.query

the problem is the filterType is from elsewhere, says it's list of array

const list = ['priceFilter', 'ageFilter', 'destinationFilter']

can I do this?

const { list.map(o => o) } = req.query which means

const { priceFilter , ageFilter, destinationFilter } = req.query

Hanz
  • 499
  • 7
  • 18

1 Answers1

0

You can filter request's query parameters according to the filterTypes array and then access the filters by iterating.

function getFilters(req, filterTypes) {
  return Object.keys(req.query).reduce((acc, k) => {
    const isAllowedFilter = filterTypes.some(type => type === k);
    if (isAllowedFilter) {
      return { ...acc, [k]: req.query[k] };
    }
    return acc;
  }, {});
}

const filterTypes = ['priceFilter', 'ageFilter', 'destinationFilter'];

const req = {
  query: {
    priceFilter: '50-100',
    ageFilter: '8-20',
    destinationFilter: 'foo',
    unknownFilter: 'unknown',
  },
};

const filters = getFilters(req, filterTypes);

Object.keys(filters).forEach(k => console.log(`${k} -> ${filters[k]}`));
teimurjan
  • 1,875
  • 9
  • 18