Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda