[英]Formatting data for Google Charts
我正在嘗試取得一些成就,以便為Google圖表正確格式化我的數據。 目前,我的數據格式如下
Array(4)
0: {Category: "cat2", Count: 11}
1: {Category: "cat4", Count: 24}
2: {Category: "cat3", Count: 52}
3: {Category: "cat1", Count: 57}
Google要求第一行為標簽,其他行為內容。 因此,就我而言,Google要求我的數據必須是這樣
let data = google.visualization.arrayToDataTable([
['Category', 'Count'],
['cat1', 11],
['cat2', 24],
['cat3', 52],
['cat4', 57]
]);
為了做到這一點,我正在做以下
generateData (data) {
return [Object.keys(data[0])].
concat(
data.map(
data => Object.values(data)
)
);
}
因此,這一切都很好,但是,我想實現另外兩個目標。 首先,我要確保數據按特定順序排列。
所以這就是我的想法,我不需要像上面一樣動態地收集類別。 這樣做的原因是因為我知道它將始終是4類,即cat1,cat2,cat3和cat4。 因此,我可以按所需順序定義類別。
generateData (data) {
let myArray = [];
const header = ["Category", "Count"];
const categories = ["cat1", "cat2", "cat3", "cat4"];
myArray.push(header);
}
但是,如何在數據數組中添加其他行,以確保其與正確的類別匹配?
我想做的第二件事是給每個類別欄自己的顏色。 根據Google文檔,在標題行中,我可以添加樣式
let myArray = [];
const header = ["Category", "Count", { role: 'style' }];
const categories = ["cat1", "cat2", "cat3", "cat4"];
const colors = ["red", "blue", "silver", "yellow"];
myArray.push(header);
但是,對於我的數據數組中的其他行,我需要為每個類別添加適當的顏色。 所以我要的最終數組應該看起來像這樣
[
["category", "Count", { role: 'style' }],
["cat1", "11", "red"],
["cat2", "24", "blue"],
["cat3", "52", "silver"],
["cat4", "57", "yellow"]
];
如何通過傳遞的初始數據來實現這一目標?
謝謝
您可以在任何數組上使用forEach
,然后創建一個包含三個具有對應值的值的數組。
let myArray = []; const header = ["Category", "Count", { role: 'style' }]; const data = [ {"Category":"cat3","Count":59}, {"Category":"cat1","Count":109}, {"Category":"cat2","Count":120}, {"Category":"cat4","Count":57} ] const obj = data.reduce((ac,{Category, Count}) => (ac[Category] = Count,ac),{}); const categories = ["cat1", "cat2", "cat3", "cat4"]; const count = [57, 11, 52, 24]; const colors = ["red", "blue", "silver", "yellow"]; myArray.push(header); categories.forEach((x,i) => { myArray.push([x,obj[x],colors[i]]); }) console.log(myArray)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.