![](/img/trans.png)
[英]Can I count how many times a name appears in a specific locus in JSON?
[英]Count how many times a specific Date appears in a JSON
各位早安
我有一個變量convertObjChart包含以下代碼,每次前端用戶選擇不同的時間段時都會更新:
"[{\"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都顯示為一行中的一個名稱。
#2:在Y上表示該特定日期出現錯誤代碼的次數。
#3:在X上表示 JSON 內每一天的 label日期。
問:如何計算 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 轉換為 Object
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 }
*/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.