Tengo que filtrar JSON por parámetros.
Obtener método: http://localhost:5000/api/car?bodyTypeId=2 (Necesito obtener objetos JSON solo con bodyTypeId = 2. Pero desafortunadamente los obtengo todos):
[ { "id": 1, "bodyTypeId": 1, //bodyTypeId not equal to 2 "carManufacturerId": 1 }, { "id": 2, "bodyTypeId": 2, "carManufacturerId": 1 }, { "id": 3, "bodyTypeId": 2, "carManufacturerId": 1 } ]Controlador:
async getAll(req, res){ //filter let {carManufacturerId, bodyTypeId} = req.body let cars; if (!carManufacturerId && !bodyTypeId){ cars = await Car.findAll() } if (carManufacturerId && !bodyTypeId){ cars = await Car.findAll({where: {carManufacturerId}}) } if (!carManufacturerId && bodyTypeId){ cars = await Car.findAll({where: {bodyTypeId}}) } if (carManufacturerId && bodyTypeId){ cars = await Car.findAll({where: {bodyTypeId,carManufacturerId}}) } return res.json(cars) }Enrutador:
router.get('/', CarController.getAll)Sus datos son una matriz, por lo que puede usar el método de filtro. consulte aquí https://www.w3schools.com/jsref/jsref_filter.asp
const data = [ { "id": 1, "bodyTypeId": 1, "carManufacturerId": 1 }, { "id": 2, "bodyTypeId": 2, "carManufacturerId": 1 }, { "id": 3, "bodyTypeId": 2, "carManufacturerId": 1 } ] let result = null data.filter(json => { if(json.bodyTypeId = 2) { result = json } }) return resultSi solo desea filtrar desde una matriz de objetos, puede usar el método Array.filter .
const allCars = [ { "id": 1, "bodyTypeId": 1, "carManufacturerId": 1 }, { "id": 2, "bodyTypeId": 2, "carManufacturerId": 1 }, { "id": 3, "bodyTypeId": 2, "carManufacturerId": 1 } ] const result = allCars.filter(car => car.bodyTypeId == bodyTypeId);