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