我正在尝试使用Chart.js创建柱状图。我卡在了尝试基于用户状态创建分组柱状图上。这是数据:
[{statusId: 0, firstName: "Joe", status: "appealed", count: 1},
{statusId: 0, firstName: "Jane", status: "approved", count: 100},
{statusId: 0, firstName: "Smith", status: "approved", count: 63},
{statusId: 0, firstName: "Mike", status: "approved", count: 63},
{statusId: 0, firstName: "Ken", status: "approved", count: 35},
{statusId: 0, firstName: "Kim", status: "approved", count: 193},
{statusId: 0, firstName: "Joe", status: "approved", count: 1},
{statusId: 0, firstName: "Jane", status: "closed", count: 1},
{statusId: 0, firstName: "Joe", status: "concluded", count: 1},
{statusId: 0, firstName: "Jane", status: "denied", count: 6},
{statusId: 0, firstName: "Smith", status: "denied", count: 9},
{statusId: 0, firstName: "Mike", status: "denied", count: 1},
{statusId: 0, firstName: "Mark", status: "denied", count: 8},
{statusId: 0, firstName: "Ken", status: "denied", count: 2},
{statusId: 0, firstName: "Kim", status: "denied", count: 20},
{statusId: 0, firstName: "Joe", status: "denied", count: 2},
{statusId: 0, firstName: "Joe", status: "transferred", count: 1}]
根据这些数据,我需要为用户创建一个图表,其中x轴是用户的每个状态计数。可以通过以下数据集的数组在Chartjs中轻松完成:
datasets:[{
data: [//some counts for a group],
},
{
data: [// counts for another group],
}
// and so on
}]
问题在于我需要根据状态对这些数据进行分组。因此,我能想到的一个解决方案是:
angular.forEeach(data, function(val)){
switch(val.status){
case 'approved':
// add count to an approved count array
break;
case 'appealed':
// add count to appealed count array
break;
}
}
我认为这里存在问题。如果他们创建了另一个状态,例如“pending”,那么我就必须回去更改代码。有没有办法通过状态分组对象并创建每个组的计数数据数组,然后将其用于数据集?
我刚刚在Pluralsight上报名了JavaScript课程,所以学习高级JavaScript还需要一段时间。在此期间,有人可以向我展示解决这个难题的正确且有效的方法吗?
例子
Chart.js 要求数据格式如下:
var data = {
labels: ['Joe', 'Jane', 'Smith', 'Mike', 'Ken', 'Kim', 'Mark'],
datasets: [
{
label: 'Appealed',
fillColor: '#382765',
data: [1,0,0,0,0,0,0]
},
{
label: 'Approved',
fillColor: '#7BC225',
data: [1, 100, 63, 63, 35, 193,0]
},
{
label: 'Denied',
fillColor: '#2196F3',
data: [2, 6, 9, 1, 2, 20, 8]
},
]
}
所以,这里发生的是针对
labels
中的每个item
,datasets
数组内部的data
数组中有status
即label
的count
。例如:对于Appealed
label
的data
数组:1
是Joe
的appealed
计数,其余用户的计数为0。