I have this JSON Object:
{
"columnNames": [
"Incident ID",
"IncidentType"
],
"rows": [
[
"3599590",
"Telecommuting/VWA Empl- Initiate"
],
[
"3599601",
"Telecommuting/VWA Empl- Initiate"
]
]
}
I would like to convert that object in Javascript to this object:
{
reportResults: [{
"Incident ID": "3599590",
"IncidentType": "Telecommuting/VWA Empl- Initiate"
},
{
"Incident ID": "3599591",
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}
]
}
I have tried using the push function in the following example:
VWA_Output = {
"columnNames": [
"Incident ID",
"IncidentType"
],
"rows": [
[
"3599590",
"Telecommuting/VWA Empl- Initiate"
],
[
"3599601",
"Telecommuting/VWA Empl- Initiate"
]
]
};
JSTest_JSON_Var1 = {
reportResults: []
};
for (i in VWA_Output.rows) {
for (var j in VWA_Output.rows[i]) {
var key = VWA_Output.columnNames[j];
var value = VWA_Output.rows[i][j]
JSTest_JSON_Var1.reportResults.push({
[key]: value
});
}
}
console.log(JSTest_JSON_Var1);
However, it seems to create the the object like this with the collection as an individual array element:
{
[{
"reportResults": [{
"Incident ID": "3599590"
}, {
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}
},
{
"Incident ID": "3599591"
},
{
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}
}]
}
I would like the collection of columns and rows to be a single record collection in the array:
{
"reportResults": [{
"Incident ID": "3599590",
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}, {
"Incident ID": "3599591",
"IncidentType": "Telecommuting/VWA Empl- Initiate"
}]
}
Thanks!
obj[key] = valueand finally outside the innerloop push that object toJSTest_JSON_Var1.reportResults. But I think you should just go with the more readable answers provided below.