我有关联数组,我想使用 Chart.JS 库显示它。
My Array:
array:4 [▼
0 => array:3 [▼
"faculty" => "Information Technology"
"category" => "ELearning"
"counter" => 2
]
1 => array:3 [▼
"faculty" => "Information Technology"
"category" => "Webex"
"counter" => 2
]
2 => array:3 [▼
"faculty" => "Masscom"
"category" => "ELearning"
"counter" => 3
]
3 => array:3 [▼
"faculty" => "Masscom"
"category" => "Webex"
"counter" => 3
]
]
What I am trying to do:
我试图展示: - 底部的功能作为标签 - 对于每个教师,我想显示所有类别及其计数器
例如:
1) 信息技术具有值(value)为 2 的电子学习类别,并且具有值(value)为 2 的 Webex 类别
2) Masscom 具有值为 3 的 ELearning 类别,并且具有值为 3 的 Webex 类别
JS Code:
var faculties = ['Information Technology', 'Masscom'];
var f = document.getElementById("mybarChart");
new Chart(f, {
type: "bar",
data: {
labels: faculties,
datasets: ....
},
})
最佳答案
本质上,您需要为每个类别提供一个数据集。每个数据集都需要每个教师的数据条目。
使用下面的代码,您将得到一个如下所示的图表:
// this will get distinct faculty and sort
const faculties = [...new Set(data.map(v => v['faculty']))].sort();
// this will get distinct category and sort
const categories = [...new Set(data.map(v => v['category']))].sort();
const datasets = categories.map(category => ({
label: category,
data: faculties.map(faculty => {
const value = data.find(v => v['faculty'] === faculty && v['category'] === category);
return value['counter'];
})
}));
const canvas = document.getElementById('mybarChart');
new Chart(canvas, {
type: 'bar',
data: {
labels: faculties,
datasets: datasets
}
});
我创建了一个 jsfiddle 到 show the code running .
关于javascript - 使用 Chart.js 和关联数组生成条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55661360/