2

我正在尝试将对象解析为 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值来改变。这样做相对容易,因为我可以将对象反转为数组,但真正的问题是:是否可以将对象解析为图表的数据而不是数组?. 谢谢!

4

1 回答 1

2

与您在评论中所说的不同,实际上可以做您想做的事情。

您只需要使用 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]);
        }
    }
}

有关最终结果,请参阅此 jsFiddle

于 2016-09-01T13:37:41.370 回答