After fetching JSON data from an API, I am using the map function to create my own object structure.
The data consists of multiple objects. An example of the data structure is as follows:
{
"data": {
"job": [
{
"jobNumber": "1",
"jobTasks": {
"jobTask": [
{
"total": { "amountString": "10.00" }
},
{
"total": { "amountString": "10.00" }
}
]
}
},
{
"jobNumber": "2",
"jobTasks": {
"jobTask": [
{
"total": { "amountString": "20.00" }
},
{
"total": { "amountString": "20.00" }
}
]
}
},
{
"jobNumber": "3",
"jobTasks": {
"jobTask": [
{
"total": { "amountString": "30.00" }
},
{
"total": { "amountString": "30.00" }
}
]
}
}
]
}
}
Based on the provided example, I aim to achieve the following results:
jobNumber: 1 - Total 20. jobNumber: 2 - Total 40. jobNumber: 3 - Total 60.
Below is the code snippet that I am using:
var array = response.data.map(function(item, array) {
var sumTaskTotal = item.jobTasks.reduce(function(sumTaskTotal, item, index) {
if (item !== null && item.total !== null) {
sumTaskTotal += item.total.amountString;
return sumTaskTotal;
}
}, 0);
array = response.data.map(item => ({
jobNumber: item.jobNumber,
sumTaskTotal: sumTaskTotal,
}));
}
However, the sum calculation keeps accumulating, resulting in:
jobNumber: 1 - Total 120. jobNumber: 120 - Total 120. jobNumber: 3 - Total 120.
I have experimented with for loops but haven't yet found a solution.