0

I have a JSON object that looks like this:

  "Classes": [
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "2"
    },
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "8"
    },
    {
      "ID": "ENGLISH101",
      "Class": "English",
      "StudentCount": "13"
    }]

This JSON object is stored in $scope. How can I first group the data by Class and then SUM the StudentCount?

So the resulting JSON object would look something like this - ideally stored as a new scope variable:

  "Classes": [
    {
      "ID": "MATH101",
      "Class": "Math",
      "StudentCount": "10"
    },
    {
      "ID": "ENGLISH101",
      "Class": "English",
      "StudentCount": "13"
    }]

I've searched everywhere, and the only thing I can find are examples of doing this in conjunction with an ng-repeat, but I'm not using that here. I just need to massage this data for use in angular-chartjs.

Thank you very much for taking the time to look at my question.

1 Answer 1

1

the transformation is just a logical part, your ng-repeat and all you can use then to render that in UI how you want.

here I am writing a function that will do the job for you

function populateSumArray(inputClasses) {
    opClasses = [];
    inputClasses.forEach(function(item) {
        var existing = opClasses.find(function(each) {
            return each.Class === item.Class;
        });
        if (existing) {
            existing.StudentCount = parseInt(existing.StudentCount) + parseInt(item.StudentCount);
        } else {
            opClasses.push(item);
        }
    });
    return opClasses;
}

and you can call this to transform it to a new array (calculated) and store it whereever you need. If you want to update the same scope variable then here is an example

$scope.Classes = populateSumArray($scope.Classes)

hope, it helps :)

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your help! I'm getting inputClasses.forEach is not a function Any ideas?
pass an array to the function, what exactly you are passing?
I have the JSON object in a variable called $scope.classes. How do I pass this variable to your function so that it transforms the JSON?
and your object $scope.classes have an property called Classes right? then try $scope.classes.Classes = populateSumArray($scope.classes.Classes)
AHA! That did it! You're the man! But real quick - what if my StudentCount wasn't always an integer? What if it had decimals like 1.5? It looks like the parseInt is interfering with the decimals.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.