I am receiving data from my server and when I output it to the console I get the following structure
(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 = [
["Category", "Count"],
["cat1", 11]
["cat2", 14]
["cat3", 21]
]
So the first row should be the keys, in this case Category and Count. Then each following row should contain the values for Category and Count.
I got a bit confused at first and with some help, came up with the following
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);
You can see from the output that the above puts the values for Category in row one, instead of the keys. So how can I achieve the output I am after whereby the keys are row one, and the values for those respective keys are in the following rows?
Thanks
2 Answers 2
You can start by having a nested accumulator array with category and count
const chartData = {
chartOne: [{
Category: "cat1",
Count: 11
},
{
Category: "cat2",
Count: 14
},
{
Category: "cat3",
Count: 21
}
]
}
const newChartData = chartData.chartOne.reduce((acc, item) => {
acc.push([item.Category, item.Count])
return acc;
}, [
['Category', 'Count']
]);
console.log(newChartData);
Comments
You can use, array.map() and return the array of elements like, [item.Category, item.Count].
And using array.unshift(), you can push the keys as the first value like, data.unshift(["Category", "Count"]).
If you have dynamic keys then you could also use,
data.unshift(Object.keys(chartData.chartOne[0])) .
Solution as follows:
const chartData = {
chartOne: [{
Category: "cat1",
Count: 11
},
{
Category: "cat2",
Count: 14
},
{
Category: "cat3",
Count: 21
}
]
}
const data = chartData.chartOne.map(item => [item.Category, item.Count]);
data.unshift(Object.keys(chartData.chartOne[0]))
console.log(data)