计算特定日期在 JSON 中出现的次数

Count how many times a specific Date appears in a JSON

早上好伙计们,

我有一个变量 convertedObjChart 包含以下代码,每次前端用户选择不同的时间段时都会更新该代码:

"[{\"ErrorCode\":\"4212\",\"Date\":\"2019-12-17\"},{\"ErrorCode\":\"1\",\"Date\":\"2020-01-23\"},{\"ErrorCode\":\"4233\",\"Date\":\"2020-02-21\"},{\"ErrorCode\":\"4233\",\"Date\":\"2020-02-24\"},{\"ErrorCode\":\"1\",\"Date\":\"2020-07-02\"},{\"ErrorCode\":\"1006\",\"Date\":\"2020-07-15\"},{\"ErrorCode\":\"4245\",\"Date\":\"2020-07-16\"},{\"ErrorCode\":\"9420\",\"Date\":\"2020-08-17\"},{\"ErrorCode\":\"9450\",\"Date\":\"2020-08-17\"},{\"ErrorCode\":\"1\",\"Date\":\"2020-11-09\"},{\"ErrorCode\":\"4\",\"Date\":\"2020-11-09\"},{\"ErrorCode\":\"4245\",\"Date\":\"2020-11-09\"}]";

#1: 需要将这个JSON字符串输入到多折线图中,所以显示每个ErrorCode作为一行中的 name

#2:表示在 Y 上出现 ErrorCode 的次数具体日期。

#3:在 X 上表示标签 Date 中的每一天JSON.

问:如何计算某一天在 JSON 中出现了多少次?

请注意,每次用户更新所选时间段时,此字符串的长度都会发生变化,根据在该时间段内发现的错误数量,长度会变大或变小。

这是我用于测试的图表(不是正确的图表,因为只有一行):

var chart = new CanvasJS.Chart("chartContainer", {
            theme: "light2", // "light1", "light2", "dark1", "dark2"
            animationEnabled: true,
            zoomEnabled: true,
            title: {
                text: "Try Zooming and Panning"
            },
            data: [{
                type: "line",
                dataPoints: convertedObjChart,
            }]
        });
      
        chart.render();

您应该先将 json 转换为对象

const jsonData =
  '[{"ErrorCode":"4212","Date":"2019-12-17"},{"ErrorCode":"1","Date":"2020-01-23"},{"ErrorCode":"4233","Date":"2020-02-21"},{"ErrorCode":"4233","Date":"2020-02-24"},{"ErrorCode":"1","Date":"2020-07-02"},{"ErrorCode":"1006","Date":"2020-07-15"},{"ErrorCode":"4245","Date":"2020-07-16"},{"ErrorCode":"9420","Date":"2020-08-17"},{"ErrorCode":"9450","Date":"2020-08-17"},{"ErrorCode":"1","Date":"2020-11-09"},{"ErrorCode":"4","Date":"2020-11-09"},{"ErrorCode":"4245","Date":"2020-11-09"}]'

let data = JSON.parse(jsonData)

let calculatedResult = new Object()
data.forEach((d) => {
  calculatedResult[d.Date] = calculatedResult[d.Date]
    ? ++calculatedResult[d.Date]
    : 1
})
console.log(calculatedResult)
/**
it print out { '2019-12-17': 1,
  '2020-01-23': 1,
  '2020-02-21': 1,
  '2020-02-24': 1,
  '2020-07-02': 1,
  '2020-07-15': 1,
  '2020-07-16': 1,
  '2020-08-17': 2,
  '2020-11-09': 3 }
*/