Reputation: 3338
I am integrating chart.js into my application and to me it does not seem possible to pass an object as the data with the keys as labels.
Right now I am trying this with a regular bar chart, in which the API looks like:
data : [1,2,3]
labels: ['a','b','c']
The docs allow passing something like the below:
data: [{x:'2016-12-25', y:20}, {x:'2016-12-26', y:10}]
But only when using a time scale.
My arrays are coming from elsewhere and could easily lose their order, I would like to pass something such as:
data: [{a:1},{b:2},{c:3}]
Upvotes: 0
Views: 1272
Reputation: 697
let data = [1,2,3],
labels=['a','b','c'];
labels.forEach((item,index)=>{
data[index]={[item]:data[index]}
})
console.log(data); //[{ a: 1 }, { b: 2 }, { c: 3 }]
Upvotes: 0
Reputation: 405
If your data is like [{a:1},{b:2},{c:3}]
you can easily convert it to two arrays using
let labelArr=[];let dataArr=[];
data.forEach((item)=>{labelArr.push(Object.keys(item)
[0]);dataArr.push(item[Object.keys(item)[0]])})
This is the handily possible way, As the current API of chart.js is not having support for complex data array only alternative is to extend Chart.controller.bar from chartjs internal and then assign the same label array to it by extracting.
Upvotes: 1