Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

165
Views
How do I get ALL items and filter queried items when using Express

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!