Despite my efforts to find a solution for my issue, I couldn't locate a relevant topic. Being new to Javascript, I suspect my lack of understanding is hindering me from resolving the problem. After days of trying, I'm still unable to grasp it. Any help would be greatly appreciated - thank you.
Issue: I am attempting to map data from a JSON object retrieved from an API (Source) to a different data structure (Result). Strangely, duplicates are being generated in my assignment, even though I believe I am explicitly assigning to only one position in the data object.
I apologize for the lengthy code example, but the problem lies at the very end of it. In the debugger, I can observe that in each iteration of the loop, all values are assigned to all result series.data - despite not understanding why.
Below is my code:
function Sample(){
// Source data from the API simplified
var SourceData = {
"hits": 4,
"job": [
{
"status": "FINISHED",
"type": "IMPORT",
},
{
"status": "FAILED",
"type": "EXPORT",
},
{
"status": "RUNNING",
"type": "TRANSCODE",
},
{
"status": "FINISHED",
"type": "TRANSCODE",
}
]
};
// Helper variable
var status = [];
//Initialize Result data object
var ResultData = {
labels: [],
series: []
};
// Used to to extend the Result Data Object later
var placeholderSeries = {name:'', data: []}
// Get job types and Status from SourceData and write as labels and series.name to result object without duplicates
for (var i=0; i < SourceData.job.length; i++){
var typeExists = ResultData.labels.indexOf(SourceData.job[i].type);
var statusExists = status.indexOf(SourceData.job[i].status);
if (typeExists == -1){
ResultData.labels.push(SourceData.job[i].type);
ResultData.labels.sort();
}
if (statusExists == -1){
// Fill array with Status values without duplicates
status.push(SourceData.job[i].status);
// Fill result data with empty sub structure
ResultData.series.push(placeholderSeries);
}
}
// Write a series name for each job status corresponding with the status values of the source
for(var i=0; i < ResultData.series.length; i++)
{
// THIS LINE DOESN'T WORK AS I WOULD EXPECT
ResultData.series[i].name = status[i];
}
console.log(JSON.stringify(ResultData,null,4));
}
The Outcome I get is:
{
"labels": [
"EXPORT",
"IMPORT",
"TRANSCODE"
],
"series": [
{
"name": "RUNNING",
"data": []
},
{
"name": "RUNNING",
"data": []
},
{
"name": "RUNNING",
"data": []
}
]
}
The Expected Outcome should be:
{
"labels": [
"EXPORT",
"IMPORT",
"TRANSCODE"
],
"series": [
{
"name": "FINISH",
"data": []
},
{
"name": "FAILED",
"data": []
},
{
"name": "RUNNING",
"data": []
}
]
}