简体   繁体   English

使用 NodeJS 过滤和计数 JSON 响应

[英]Filter and count JSON Response using NodeJS

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.在这种情况下,赢:1,输:3。如何过滤和计算 response.data 和 output 所需的结果。 I have tried using filter with includes with no luck我尝试使用带有包含的过滤器但没有运气

Axios get method, filter and count: Axios 获取方法、过滤和计数:

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这是我从 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:我想 map 它并以 JSON 结果响应,如下所示:

{
    "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..."
        }
    ]
}
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);
    });

It's certainly not required to perform this work, but I like Lodash's partition function.当然不需要执行这项工作,但我喜欢 Lodash 的partition function。 This function will segment an input array into two other arrays based on a predicate.这个 function 将基于谓词将输入数组分割成另外两个 arrays。 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:我们可以像这样完成第 1 步:

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

Then complete Step 2 like this:然后像这样完成第 2 步:

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...然后,您可以构建一个 object 报告赢家和输家列表,您的计数只是这些列表的长度......

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

That last line there ( winList, loseList ) takes advantage of JavaScript's object initialization shorthand .最后一行( winList, loseList )利用了 JavaScript 的object 初始化简写

Here's a StackBlitz so you can try it out.这里有一个StackBlitz ,你可以试试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM