我正在尝试将对象解析为chart.js而不是使用数组。这是我的目标:
var obj = {
"and":2,
"two":1,
"too":1,
"mother":2
}
我想将obj
解析为chart.js,因此它会根据该对象的数据创建一个图表。例如,如果我们采用条形图,它会将and
放在Y轴的2上。其次是two
,其中Y轴为1,依此类推。
如何创建条形图:
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
。这样做相对容易,因为我可以将对象转换为数组,但真正的问题是:是否可以将对象解析为图表的数据而不是数组?。谢谢!
答案 0 :(得分:1)
与您在评论中所说的不同,实际上可以做你想做的事。
你只需要使用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。