简体   繁体   中英

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. This data has a lot of layers, need to use different parts of it for Google Charts.

So lets call my first chart 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

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.

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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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