I have an API that returns 100 rows of lots of different json data including HTTP Status:
{"data": [{"status": 409},{"status": 200},{"status": 404},{"status": 200},{"status": 200},{"status": 200}]}
And I want to make a pie chart which requires a DataTable like this:
['status', count],
['200', 4],
['404', 1],
['409', 1]
What is the most graceful way to accomplish this? I am somewhat familiar with vanilla Javascript but will accept Jquery or other solutions.
I would have thought there was a simple library (?) that would let me choose "status" from my json and it would automagically format it for a pie chart (any pie chart - although I'm trying Google Charts to begin) — but I have not found such a library.
What I have tried... I made a list of things to learn how to accomplish ... assuming there is no "library" or simple way to select, count (and maybe also order from lowest to highest) the json data for the Google or other pie chatrt, Does this look like a decent plan, or is there a better way?
Thank you for any advice.
I believe an array.reduce
loop will do the trick.
let data = {
"data": [{
"status": 409
}, {
"status": 200
}, {
"status": 404
}, {
"status": 200
}, {
"status": 200
}, {
"status": 200
}]
}
let newdata = data.data.reduce((accum, a) => {
// console.log(accum, a);
let found = 0;
accum.forEach((el, index) => {
if (el[0] == a.status) {
accum[index][1]++;
found = 1
}
})
if (!found) accum.push([a.status.toString(), 1])
return accum
}, [
['status', 'count']
]);
console.log(newdata)