I have a dataset that I'm transforming into another array so that it may be processed in a chart. I hvae the chart working, but the count key is incorrect. This is what it looks like:
export type ChartData = {
category?: string;
value?: number | string;
count?: number;
createdAt: string;
physicalActivity?: number;
};
const moodArr: ChartData[] = [];
if (data) {
data.assessments.data.forEach((assessment) => {
const { responses } = assessment.questionnaires[0];
responses.forEach((response) => {
response.value.forEach((moodValue) => {
console.log(moodValue)
moodArr.push({
value: toMoodMap(moodValue),
count: (moodValue || 0) + 1,
createdAt: moment(assessment.createdAt).format('YYYY-MM-DD'),
})
});
});
});
count doesn't work because moodValue will return as an integer. toMoodMap will only map to a String depending on the moodValue. However, count will just take its original value (which will be 0 - 4) instead of keeping a count of the times its returned. Is there any way to keep a count for this?
forEach takes a second parameter which is the index of the item, so if you just want the count of how many times and item is pushed to the array you could do something like
const moodArr: ChartData[] = [];
if (data) {
data.assessments.data.forEach((assessment) => {
const { responses } = assessment.questionnaires[0];
responses.forEach((response,i) => {
response.value.forEach((moodValue,j) => {
console.log(moodValue)
moodArr.push({
value: toMoodMap(moodValue),
count: response.value.length*i + j,
createdAt: moment(assessment.createdAt).format('YYYY-MM-DD'),
})
});
});
});