Apexcharts Barchart Vertical Categories Logic In Reactjs?
I am having a problem trying to figure out how to display the correct data to the correct category. My data is in this format from a json API: { 'name' : 'product1', 'records':
Solution 1:
The following code will create a series object for each Product. Each Product will have its own data array. Where each number corresponds sequentially to a month. A 0 value is added in place for a month that was not utilized in the data-set for that product.
Example dataset:
let data = [{
"name" : "product1",
"records": "5",
"month" : "Jan",
},
{
"name" : "product1",
"records": "10",
"month" : "Feb",
},
{
"name" : "product1",
"records": "20",
"month" : "Mar",
},
{
"name" : "product2",
"records": "5",
"month" : "Feb",
},
{
"name" : "product1",
"records": "5",
"month" : "May",
},
{
"name" : "product2",
"records": "5",
"month" : "Jun",
}
]
This creates an array of months that were used in the data-set. No duplicates. We will use it to map the corresponding data-values of each product in their specific month.
Creating Categories:
let months = data.map((item) => item.month).filter((item, index, array) => array.indexOf(item) == index)
Creating Series:
const productTotals = data.reduce((obj, curr) => {
if(!obj[curr.name]){
obj[curr.name] = []
}
obj[curr.name][months.indexOf(curr.month)] = parseInt(curr.records)
return obj
}, {})
const series = Object.entries(productTotals).map(([name, prodArr]) => {
return {
name: name,
data: months.map((month, monthIndex) => {
if(!prodArr[monthIndex]){
return0
} else {
return prodArr[monthIndex]
}
})
}
})
Then simply update the properties with your new series data and categories.
this.state= {
barChart: {
options: {
plotOptions: {
xaxis: {
categories: [...months]
}}}
series: [...series]}
Post a Comment for "Apexcharts Barchart Vertical Categories Logic In Reactjs?"