1

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

asked Oct 8, 2020 at 9:29

2 Answers 2

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

answered Oct 8, 2020 at 9:33
Sign up to request clarification or add additional context in comments.

Comments

1

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)

answered Oct 8, 2020 at 9:42

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.