Home > Net >  How do I get ALL items and filter queried items when using Express
How do I get ALL items and filter queried items when using Express

Time:03-10

I have the following Array:

const cars = [
  { make: 'Toyota', model: '4Runner', bodyType: 'SUV' },
  { make: 'Audi', model: 'A4', bodyType: 'Sedan' },
  { make: 'Ford', model: 'F-150', bodyType: 'Truck' },
]

I would like to send the cars array when visiting /cars endpoint. But when the user adds a query to the endpoint such as /cars?bodyType=SUV it should only return the filtered items.

So far I have:

app.get('/cars', (req, res) => {
  const bodyType = req.query.bodyType
  const filteredCars = cars.filter((car) => car.bodyType === bodyType)
  res.send(req.query ===  ? cars : filteredCars)
})

I know i'm probably way off.

CodePudding user response:

The following code works loops through all the keys in the query and compares it with the car object.

app.get('/', (req, res) => {
  const filter = req.query
  const haveFilters = Object.keys(filter).length
  let filteredCars = cars
  if(haveFilters){
    filteredCars = cars.filter((car) => {
      for(let key in filter){
        if(car[key] !== filter[key]) return false
      }
      return true
    })
  }

  res.send(filteredCars)
})
  • Related