Matthew Ham Matthew Ham - 6 months ago 12
AngularJS Question

Javascript: Accessing an object property by key

I'm looking to make my code more efficient. I've written it like this because I can't find a way to access object properties by their respective keys. I'd ideally like to use a for loop to shorten this enormous chunk of code down. I'm open to restructuring my object, if that will help.

if (response.data[i].code == 'P01') {
$scope.production['P01'] += response.data[i].hours;
} else if (response.data[i].code == 'P02') {
$scope.production['P02'] += response.data[i].hours;
} else if (response.data[i].code == 'P03') {
$scope.production['P03'] += response.data[i].hours;
} else if (response.data[i].code == 'P04') {
$scope.production['P04'] += response.data[i].hours;
} else if (response.data[i].code == 'P05') {
$scope.production['P05'] += response.data[i].hours;
} else if (response.data[i].code == 'P06') {
$scope.production['P06'] += response.data[i].hours;
} else if (response.data[i].code == 'P07') {
$scope.production['P07'] += response.data[i].hours;
} else if (response.data[i].code == 'P08') {
$scope.production['P08'] += response.data[i].hours;
}


As you can imagine, $scope.production is an object like such:

$scope.production = {'P01' :0, 'P02' : 0, 'P03' :0};

Answer
var data = response.data[i];
$scope.production[data.code] += data.hours;