[英]How to filter JSON objects?
我必须通过参数过滤 JSON 。
获取方法: http://localhost:5000/api/car?bodyTypeId=2 (我需要获取 JSON 对象,只有 bodyTypeId = 2。但不幸的是我得到了所有对象):
[
{
"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.get('/', CarController.getAll)
您的数据是一个数组,因此您可以使用过滤器方法。 在这里查看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
如果您只想从对象数组中过滤,可以使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.