Is there a more efficient way to transform an array of objects with JavaScript? I'm new to working with JavaScript and struggling to achieve the desired formatted array. Any help would be greatly appreciated, thank you.
This is what I've attempted...
// Trying to get the formatted reports array
$scope.reports = [];
var num = 1;
for(var i=0; i<$scope.reports_data.length; i++) {
var row = {
"reviewer_1" : "",
"reviewer_2" : "",
"reviewer_3" : "",
"created_at" : ""
};
if(num == $scope.reports_data[i].report_id) {
row.created_at = $scope.reports_data[i].created_at;
if($scope.reports_data[i].stage == 1 ) {
row.reviewer_1 = $scope.reports_data[i].full_name;
} else if($scope.reports_data[i].stage == 2) {
row.reviewer_2 = $scope.reports_data[i].full_name;
} else {
row.reviewer_3 = $scope.reports_data[i].full_name;
}
}
$scope.reports.push(row);
num += 1;
}
Before:
var raw_arr = [
{
"created_at" :"2016-05-04T16:45:07.000Z",
"full_name" :"Dick",
"report_id" : 1,
"stage" : 1
},
{
"created_at" :"2016-05-04T16:45:07.000Z",
"full_name" :"Tom",
"report_id" : 1,
"stage" : 2
},
{
"created_at" :"2016-05-04T16:45:07.000Z",
"full_name" :"Harry",
"report_id" : 1,
"stage" : 3
},
{
"created_at" :"2016-05-04T16:45:07.000Z",
"full_name" :"John",
"report_id" : 2,
"stage" : 1
},
{
"created_at" :"2016-05-04T16:45:07.000Z",
"full_name" :"Mike",
"report_id" : 2,
"stage" : 2
},
{
"created_at" :"2016-05-04T16:45:07.000Z",
"full_name" :"Charles",
"report_id" : 2,
"stage" : 3
}
];
After:
var formatted_arr = [
{
"created_at": "2016-05-04T16:45:07.000Z",
"report_id": 1,
"reviewer_1": "Dick",
"reviewer_2": "Tom",
"reviewer_3": "Harry",
},
{
"created_at": "2016-05-04T16:45:07.000Z",
"report_id": 2,
"reviewer_1": "John",
"reviewer_2": "Mike",
"reviewer_3": "Charles",
}
];