繁体   English   中英

格式化Google图表的数据

[英]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.

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