I have to filter JSON by parameters.
Get method : http://localhost:5000/api/car?bodyTypeId=2 (I need to get JSON objects only with bodyTypeId = 2. But unfortunately i getting them all):
[
{
"id": 1,
"bodyTypeId": 1, //bodyTypeId not equal to 2
"carManufacturerId": 1
},
{
"id": 2,
"bodyTypeId": 2,
"carManufacturerId": 1
},
{
"id": 3,
"bodyTypeId": 2,
"carManufacturerId": 1
}
]
Controller:
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)
}
Router:
router.get('/', CarController.getAll)
Your data is an array so you can use filter method. check here 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 result
If you just want to filter from an array of objects you can use the Array.filter method.
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);