I am trying to extract data from JSON data using .map() in javascript. The data extract needs to injected in stacked bar chart .
I am trying to do similar to this question : Stacked bar charts in Chart.js with JSON data but in my case I want total runs per season that will be the height of barchart and the total height of stacked-barchart will be divided into 3 stacks.
check this for stacked bar chart: https://gionkunz.github.io/chartist-js/examples.html#stacked-bar
My JSON data:
const batdata=[
{"season":2008,
"runs":25,
"tournamentName":"XYZ"
},
{"season":2008,
"runs":125,
"tournamentName":"ABC"
},
{"season":2008,
"runs":825,
"tournamentName":"PQR"
},
{"season":2009,
"runs":425,
"tournamentName":"XYZ"
},
{"season":2009,
"runs":255,
"tournamentName":"ABC"
},
{"season":2010,
"runs":275,
"tournamentName":"XYZ"
},
{"season":2010,
"runs":675,
"tournamentName":"ABC"
}
];
export default batdata;
In chart.js:
import React, { Component } from 'react';
import batdata from './batdata';
const uniq = a => [...new Set(a)]
const uniqueseason = uniq(
batdata.map( newdata => newdata.season)
)
const runsperseason = batdata.map( newdata => {
})
class Chart extends Component {
render(){
return(
<div>
</div>
)}
}
export default Chart;
I am using .map() to get unique season and then again nested map() to get runs for particular season for particular tournamentName. How can I parse the data external json file. The final data should look like this:
labels = [2008,2009 2010]
Chartdata = [
[25, 125, 825] <--- Height of barchart = 825+25+125 and it will have 3 stacks because there are 3 tournamentName
[425, 255, 0] <-- tournamentName: PQR not present in season 2009 so 3rd element zero
[275, 675, 0] <---tournamentName: PQR not present in season 2010 so 3rd element zero
]
I want to extract the data and store it in 3 data in the form of 3 arrays:
1)Runs in season 2008 for tournamentName: XYZ,ABC, PQR
2)Runs in season 2009 for tournamentName: XYZ, ABC, PQR
3)Runs in season 2010 for tournamentName: XYZ, ABC, PQR
After storing data in 3 different arrays we can just use destructuring operator ... to unpack array elements and populate the chartdata.