【问题标题】:How to filter JSON objects?如何过滤 JSON 对象?
【发布时间】:2022-01-08 16:37:47
【问题描述】:

我必须按参数过滤 JSON。

获取方法:http://localhost:5000/api/car?bodyTypeId=2(我只需要使用 bodyTypeId = 2 获取 JSON 对象。但不幸的是我得到了所有对象):

[
    {
         "id": 1,
         "bodyTypeId": 1,  //bodyTypeId not equal to 2
         "carManufacturerId": 1
    },
    {
        "id": 2,
        "bodyTypeId": 2,
        "carManufacturerId": 1
    },
    {
        "id": 3,
        "bodyTypeId": 2,
        "carManufacturerId": 1
    }
]

控制器:

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)

【问题讨论】:

  • 控制器中的 Car 是什么

标签: javascript node.js json


【解决方案1】:

如果您只想从对象数组中过滤,可以使用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);

【讨论】:

    【解决方案2】:

    您的数据是一个数组,因此您可以使用过滤器方法。 在这里查看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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-02
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-01-25
      相关资源
      最近更新 更多