Home > Net >  How can I filter a JSON data in Node.js using Axios?
How can I filter a JSON data in Node.js using Axios?

Time:11-15

I'm newbie Back-end developer and I'm trying to build a REST API with Node.js to get the deals won from Pipedrive. I already have a function to get all deals using Axios, and it is working just fine, but I need to filter its response to send me just the ones with "won" status. I've created some deals in the Pipedrive with different status, like "won", "lost", and "open". I had a function "getAllDeals" that send me all those ones in JSON. I tried to adapt it in many different ways with no success.

I call this function in my route /deals:

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

This is my function, which is working, to get all the deals:

 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)
        }
    }

And this one is my last try to filter its response data:

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)
        }
    }

I hope there is a simple way to do it.

CodePudding user response:

Not sure what's response.where. You can use lodash.where module to help you with this. depends on the response structure, you can use lodash.where to extract the relevant data you need. So your code should like this:

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)
    }
}

of course don't forget to install the module npm i lodash.where

CodePudding user response:

You can use Array.prototype.filter for filtering your deals based on what you need. Something like this should work.

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