0👍
✅
I would do something like this:
- Place the items in an array so they are more easily managed;
- Create an array with the keys you need in your datasets: (wbc,vitamin,etc…) and custom settings for each key ( bg-color, etc… );
- Reduce the keys array to a datasets array containing objects with the shape you expect:
const items = [{
id: 2,
customer_id: 4,
date: '2019-05-15T21:00:00.000Z',
wbc: 15,
vitamin: 14,
},
{
id: 3,
customer_id: 4,
date: '2022-05-22T21:00:00.000Z',
wbc: 20,
vitamin: 5,
},
];
const keys = [{
type: 'wbc',
settings: {
backgroundColor: '#003f5c',
pointRadius: 8,
pointHoverRadius: 8,
},
},
{
type: 'vitamin',
settings: {
backgroundColor: '#ffa600',
pointRadius: 8,
pointHoverRadius: 8,
},
},
];
const datasets = keys.reduce((a, k) => {
const o = {
label: k.type.toUpperCase(),
data: items.map((i) => ({
x: new Date(i.date).toLocaleDateString(),
y: i[k.type],
})),
...k.settings,
};
a.push(o);
return a;
}, []);
console.log(datasets);
Source:stackexchange.com