I have these data
[
{
"Month": 2,
"SubjectID": 25,
"TitleName": "TEST32",
"Average": 85
},
{
"Month": 4,
"SubjectID": 1,
"TitleName": "TEST",
"Average": 63
},
{
"Month": 4,
"SubjectID": 25,
"TitleName": "TEST32",
"Average": 88
}
]
i want to transform this into array object that will base on subject id
and the month
.
I don’t know if this is possible.
but i want to create a year array where the average
will display in array index of created array base on month
number.
Output like this
{
name: 'TEST',
data: [0, 0, 0, 63, 0, 0, 0, 0, 0, 0, 0, 0]
},
{
name: 'TEST32',
data: [0, 85, 0, 88, 0, 0, 0, 0, 0, 0, 0, 0]
}
2
Answers
First create an empty object called year, which will store the data for each SubjectID. We then loop through each item in the data array and check if the SubjectID has been seen before. If it hasn’t, we create a new object for it with an empty data array of length 12 (one for each month). If it has been seen before, we simply update the existing object’s data array for the current month with the Average value.
Finally, we convert the year object into an array of objects using Object.values, and assign it to yearArray. This array contains one object for each unique SubjectID in the original data array, with the name property set to the TitleName and the data property set to an array of length 12 with the Average values in the appropriate positions.
You could use
Array#reduce
with an object to store the 12 averages for each name.