简体   繁体   中英

How to GROUP and SUM json data using angular/ionic?

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.

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 :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM