【问题标题】:How can I filter a JSON data in Node.js using Axios?如何使用 Axios 在 Node.js 中过滤 JSON 数据?
【发布时间】:2021-12-26 05:13:18
【问题描述】:

我是新手后端开发人员,我正在尝试使用 Node.js 构建一个 REST API 以从 Pipedrive 赢得交易。我已经有一个使用 Axios 获得所有交易的功能,它工作得很好,但我需要过滤它的响应,只向我发送具有“赢得”状态的那些。我在 Pipedrive 中创建了一些具有不同状态的交易,例如“赢”、“输”和“开”。我有一个函数“getAllDeals”,它以 JSON 格式向我发送所有这些。我尝试以多种不同的方式对其进行调整,但均未成功。

我在路由 /deals 中调用了这个函数:

router.get('/deals', controller.getAllDeals)

这是我的功能,正在运行,以获取所有交易:

 async getAllDeals(_, res){

        try {
            const response = await axios.get(`${PIPE_URL}?api_token=${PIPE_TOKEN}`)
            return res.json(response.data)
        }
        catch (err) {
            console.log(err)
        }
    }

这是我最后一次尝试过滤其响应数据:

async getAllDeals(_, res){

        try {
            const response = await axios.get(`${PIPE_URL}?api_token=${PIPE_TOKEN}`)
            const deals = res.json(response.data)
            const dealsWon = response.where(deals, {status: "won"})
            return dealsWon
        }
        catch (err) {
            console.log(err)
        }
    }

我希望有一个简单的方法来做到这一点。

【问题讨论】:

标签: node.js json rest filter axios


【解决方案1】:

不确定response.where 是什么。你可以使用lodash.where 模块来帮助你。取决于响应结构,您可以使用lodash.where 提取您需要的相关数据。所以你的代码应该是这样的:

const where = require("lodash.where");

async getAllDeals(_, res){

    try {
        const response = await axios.get(`${PIPE_URL}?api_token=${PIPE_TOKEN}`)
        const deals = res.json(response.data)
        const dealsWon = where(deals, {status: "won"})
        return dealsWon
    }
    catch (err) {
        console.log(err)
    }
}

当然不要忘记安装模块npm i lodash.where

【讨论】:

    【解决方案2】:

    您可以使用Array.prototype.filter 根据您的需要过滤您的交易。这样的事情应该可以工作。

    const dealsWon = deals.filter(deal => deal.status === "won")
    

    【讨论】:

      【解决方案3】:

      我在 Pipedrive 文档中读到 satus 是一个查询参数,它将按提供的特定状态过滤交易:?open=Open?won=Won?lost=Lost

      我以这种方式在我的 axios 请求中插入查询:

      const response = await axios.get(`${PIPE_URL}?status=Won&api_token=${PIPE_TOKEN}`)
      

      在我这样做之后,我的请求只返回了“赢”状态的交易。

      【讨论】:

        猜你喜欢
        • 2021-07-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-20
        • 2012-08-09
        • 2020-12-15
        • 1970-01-01
        相关资源
        最近更新 更多