Matthew Ham Matthew Ham - 1 year ago 61
AngularJS Question

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 ([i].code == 'P01') {
$scope.production['P01'] +=[i].hours;
} else if ([i].code == 'P02') {
$scope.production['P02'] +=[i].hours;
} else if ([i].code == 'P03') {
$scope.production['P03'] +=[i].hours;
} else if ([i].code == 'P04') {
$scope.production['P04'] +=[i].hours;
} else if ([i].code == 'P05') {
$scope.production['P05'] +=[i].hours;
} else if ([i].code == 'P06') {
$scope.production['P06'] +=[i].hours;
} else if ([i].code == 'P07') {
$scope.production['P07'] +=[i].hours;
} else if ([i].code == 'P08') {
$scope.production['P08'] +=[i].hours;

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

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

Answer Source
var data =[i];
$scope.production[data.code] += data.hours;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download