2017-09-04 6 views
0

Ich habe ein Problem mit dem Lesen meiner Daten aus JSON.Wie parsen und summieren Komma getrennte Zeichenfolge von Zahlen

Dies ist mein Controller:

myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { 
console.log('abcdctrl'); 
$http.get("http://localhost:8080/api/session") 
    .then(function (response) { 
     $scope.data = response.data.session; 
    }); 

$scope.getAvg = function() { 
    var total = Number("0"); 
    for (var i = 0; i < $scope.data.length; i++) { 
     total += parseInt($scope.data[i].testing); 
    } 
    return parseInt(total/$scope.data.length); 
} 
}]); 

Das ist mein JSON

{ 
"session": [ 
    { 
     "id": 1, 
     "testing": "91,92,93,94,95,96,97", 
     "playing": "11,12,13,14,15,16,17", 
     "acc_id": 1 
    }, 
    { 
     "id": 2, 
     "testing": "101,102,103,104,105,106,107", 
     "playing": "1,2,3,4,5,6,7", 
     "player_id": 2 
    }, 
    { 
     "id": 3, 
     "testing": "111,112,113,114,115,116,117", 
     "playing": "21,22,23,24,25,26,27", 
     "acc_id": 3 
    } 
] 
} 

ich den Mittelwert der einzelnen Spieler berechnen wollen, für die Verkostung und Spiel ist und ich möchte die durchschnittliche berechnen Wert zum Testen und Spielen. Es ist mir gelungen, den gesamten JSON zu drucken, aber ich habe Probleme beim Zugriff auf ein Element in JSON.

Danke für Ihre Hilfe

+0

wo diese '$ scope.getAvg' Funktion nennen? Sie haben Testwert mit ',' seperator, es ist nicht möglich hinzuzufügen. –

+0

nein es ist nicht möglich hinzuzufügen. , getAvg ruft in html – mrkibzk

+0

'91,92,93,94,95,96,97' +' 101,102,103,104,105,106,107 'dies ist nicht möglich –

Antwort

1

Try this:

myApp.controller("abcdctrl", ['$scope', 'orderByFilter', '$http', function ($scope, orderBy, $http) { 
 
console.log('abcdctrl'); 
 
$http.get("http://localhost:8080/api/session") 
 
    .then(function successCallback(response) { 
 
     $scope.data = response.data.session; 
 
    }, function errorCallback(response) { 
 
     // called asynchronously if an error occurs 
 
     // or server returns response with an error status. 
 
}); 
 

 
$scope.getAvg = function() { 
 
    var total = Number("0"); 
 
    for (var i = 0; i < $scope.data.length; i++) { 
 
     var grades = $scope.data[i].testing.split(','); 
 
     for(var j = 0; j < grades.length; j++){ 
 
      total += parseInt(grades[j]); 
 
     } 
 
    } 
 
    return parseInt(total/$scope.data.length); 
 
} 
 
}]);

Verwandte Themen