Chartjs-Chart.js โ€“ combine data and label into a single object

1๐Ÿ‘

โœ…

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.

0๐Ÿ‘

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 }]

Leave a comment