我正在尝试将对象解析为chart.js,而不是使用数组。这是我的目标:
var obj = {
"and":2,
"two":1,
"too":1,
"mother":2
}
我想将我的obj
解析为chart.js,以便它根据该对象的数据创建一个图表。例如,如果我们采用条形图,它会将 和
放在前面,Y 轴上加 2。接下来是 two
,其中 1 位于 Y 轴上方,依此类推。
如何创建条形图:
var ctx = document.getElementById("myChart");
var data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
};
var myBarChart = new Chart(ctx, {
type: 'bar',
data: data
});
这直接取自他们的网站。我需要的只是用对象中的键更改 data.labels
以及用值更改 data.datasets[0].data
。这样做相对容易,因为我可以将对象反转为数组,但真正的问题是:是否可以将对象解析为图表的数据而不是数组?。谢谢!
最佳答案
与您在评论中所说的不同,实际上可以做您想做的事情。
您只需要使用 Chart.js 插件,它允许您在特定事件(例如更新、渲染等)之前或之后处理图表,并且它们也很容易实例:
Chart.pluginService.register({
beforeInit: function(chart) {
// This will be triggered before the chart is created
}
});
无需使用您不需要的默认数据和标签创建图表,只需添加如下所示的空数组即可:
var data = {
labels: [],
datasets: [{
label: "My dataset",
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
data: []
}]
};
然后在您的 beforeInit
事件中,您只需使用您的对象填充这些数组:
beforeInit: function(chart) {
// This is where your chart data is stored
var data = chart.config.data;
// For each item in your object
for (var key in obj) {
// This is for security - check `http://stackoverflow.com/a/684692/4864023`
if (obj.hasOwnProperty(key)) {
// Add the key as a new xAxe label ...
data.labels.push(key);
// ... and the value as a new data
data.datasets[0].data.push(obj[key]);
}
}
}
参见this jsFiddle以获得最终结果。
关于javascript - 将对象解析为 Chart.js 而不是数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38836073/