Home > other >  Filter and count JSON Response using NodeJS
Filter and count JSON Response using NodeJS

Time:01-15

I want to filter and count the amount of times "win" and "loss" is in info field. In this case win: 1 and loss: 3. How do I filter and count the response.data and output the desired result. I have tried using filter with includes with no luck

Axios get method, filter and count:

axios({
    method: "get",
    url: myUrl,
    headers: {
      "Content-type": "application/json"
    },
  })
    .then(function (response) {
        const result = response.data
                res.json(result.filter(data => {
                    if (data.data.info.includes("win")) {
                        return {
                            id: data.data.id,
                            info: data.data.info
                        }
                    }
                    return false
                 }));
      res.json(result);
    })
    .catch(function (error) {
      console.log(error);
    });

This is the response I get from response.data

{
    "data": [{
            "id": "1",
            "name": "Riza",
            "age": "34",
            "info": "dsfgfds dsfg dfsg dsfg fdsg sfg sadf sdf fsadf dfasdf asdf!"
        },
        {
            "id": "2",
            "name": "John",
            "age": "24",
            "info": "dsfgfds sdfg dfsg dsfg fdsg loss sadf sdf sadf dfasdf g!"
        },
        {
            "id": "3",
            "name": "Bill",
            "age": "ff",
            "info": "dsfgfds dsfg dfsg dsfg fdsg win sadf dfgh sadf dfasdf asdf!"
        },
        {
            "id": "4",
            "name": "Sara",
            "age": "55",
            "info": "dsfgfds sdfg dfsg dsfg fdsg loss sadf sdf sadf dfasdf g!"
        },
        {
            "id": "5",
            "name": "Elon",
            "age": "38",
            "info": "dsfgfds sdfg dfsg dsfg fdsg loss sadf sdf sadf dfasdf g!"
        }
    ]
}

I want to map it and respond with a JSON result like this:

{
    "winCount": 1,
    "lossCount": 3,
    "winList": [{
        "id": "3",
        "info": "dsfgfds dsfg dfsg dsfg fdsg win sadf dfgh sadf dfasdf asdf!"
    }],
    "lostList": [{
            "id": "2",
            "info": "dsfgfd..."
        },
        {
            "id": "4",
            "info": "dsfgfds..."
        },
        {
            "id": "5",
            "info": "dsfgfds..."
        }
    ]
}

CodePudding user response:

axios({
    method: "get",
    url: myUrl,
    headers: {
      "Content-type": "application/json"
    },
  })
    .then(function (response) {
        const result = response.data;

    const filtered = {
        winCount: 0,
        lossCount: 0,
        winList: [],
        lostList: []
    };

    result.map((el, i) => {
        if (el.info.includes('loss')) {
            filtered.lossCount  ;
            filtered.lostList.push({
                id: el.id,
                info: el.info
            });
        }
        if (el.info.includes('win')) {
            filtered.winCount  ;
            filtered.winList.push({
                id: el.id,
                info: el.info
            });
        }
    });

    console.log(filtered);

      res.json(filtered);
    })
    .catch(function (error) {
      console.log(error);
    });

CodePudding user response:

It's certainly not required to perform this work, but I like Lodash's partition function. This function will segment an input array into two other arrays based on a predicate. The first array contains the items that passed the predicate and the second array contains the items that failed. With this we perform a couple operations...

  1. Separate the winners from everything else.
  2. Separate the losers from those that weren't winners.

We can complete Step 1 like this:

const [winList, othersWin] = _.partition(data, (datum) => datum.info.includes('win'));

Then complete Step 2 like this:

const [loseList, othersWinLose] = _.partition(othersWin, (datum) => datum.info.includes('loss'));

You can then build an object that reports the list of winners and losers, and your counts are just the length of those lists...

return {
    winCount: winList.length,
    loseCount: loseList.length,
    winList, loseList
};

That last line there (winList, loseList) takes advantage of JavaScript's object initialization shorthand.

Here's a StackBlitz so you can try it out.

  •  Tags:  
  • Related