简体   繁体   English

格式化 Google 图表的数组/对象数据

[英]Formatting Array/Object data for Google Charts

on the server I load a JSON file and convert it to an array, then I return it back to the frontend.在服务器上,我加载一个 JSON 文件并将其转换为数组,然后将其返回给前端。 This data has a lot of layers, need to use different parts of it for Google Charts.这个数据有很多层,需要将它的不同部分用于 Google Charts。

So lets call my first chart chartOne.所以让我们调用我的第一个图表 chartOne。 I can obtain the data I need for this chart using dot notation我可以使用点表示法获取此图表所需的数据

console.log(this.chartData.chartOne)

This will output something like the following, it is essentially an array holding objects.这将输出如下内容,它本质上是一个包含对象的数组。

(3) [{…}, {…}, {…}]
    0:
        Category: "cat1"
        Count: 11
    1: 
        Category: "cat2"
        Count: 14
    2: 
        Category: "cat3"
        Count: 21
    

What I am trying to do is prepare this data for a bar chart.我要做的是为条形图准备这些数据。 Google expects my data to be provided in the following format Google 希望我的数据按以下格式提供

const chartData = [
    ["cat1", "cat2", "cat3"],
    [11, 14, 21]
]

So the first row should be the values for the Category, and the row under this contains their Count.所以第一行应该是 Category 的值,它下面的行包含它们的 Count。

My question is how do I prepare my data in this format?我的问题是如何以这种格式准备数据? I am trying a few things but they seem excessive and I am getting a bit stuck.我正在尝试一些东西,但它们似乎有些过分,而且我有点卡住了。 This is where I am currently at这是我目前所在的地方

Object.keys(this.chartData.chartOne).forEach(key => {
    const vmKeys = this.chartData.chartOne[key]
    Object.keys(vmKeys).forEach(key => {
        console.log(vmKeys + vmKeys[key])
    })
})

Is there a better way of doing this using something like map or some other ES6 feature?有没有更好的方法来使用 map 或其他一些 ES6 特性来做到这一点?

Thanks谢谢

Like this:像这样:

let chartOne = [
  {
    Category: "cat1",
    Count: 11,
  },
  {
    Category: "cat2",
    Count: 14,
  },
  {
    Category: "cat3",
    Count: 21,
  },
];

let out = [[], []];
for (let x of chartOne) {
  let [labels, values] = out;
  labels.push(x.Category);
  values.push(x.Count);
}

console.log(out);

// prints
=> [ [ 'cat1', 'cat2', 'cat3' ], [ 11, 14, 21 ] ]

 const chartData = { chartOne: [{ Category: "cat1", Count: 11 }, { Category: "cat2", Count: 14 }, { Category: "cat3", Count: 21 } ] } const newChartData = chartData.chartOne.reduce((acc, item) => { acc[0].push(item.Category); acc[1].push(item.Count); return acc; }, [[],[]]); console.log(newChartData);

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

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