Luca H. Luca H. - 7 months ago 79
Javascript Question

Group and summarize json data to new json object

I am using angularJS and have a JSON object from an API response which looks like the following:

var data = [
{"group": "red", "state": "running"},
{"group": "red", "state": "closed"},
{"group": "red", "state": "closed"},
{"group": "blue", "state": "running"},
{"group": "blue", "state": "running"}
];


I would like to parse this object inside a javascript function to get the following result:

var sumdata = [
{"group": "red", "running": 1, "closed": 2, "summary": 3},
{"group": "blue", "running": 2, "closed": 0, "summary": 2}
];


So, I have to group the first property called "group", then count how many objects in this group are in running state, closed state and also summarize the count of objects.

(Note:
I would not like to use extra javascript libraries like LINQ.js
)

Could yo help me please?

I tried the following, which is missing the group by and have no idea how to put that into this function:

var getSum = function (data) {

if (!data) {

$scope.data = [];
}
else {

for (var i = 0; i < data.length; i++) {

var group = data[i][0];
var status = data[i][1];

status = (status ? status.Name : "").toUpperCase();

var running = 0;
var closed = 0;

switch (status) {

case "RUNNING":
running++;
break;

case "CLOSED":
closed++;
break;

default:
break;
}
var summary = running + closed;
$scope.dataSum.push({ "group": group, "running": running, "closed": closed, "summary": summary});
}
}

};

Answer

This is a proposal with a temporary object and an Array#forEach loop in plain Javascript.

var data = [{ "group": "red", "state": "running" }, { "group": "red", "state": "closed" }, { "group": "red", "state": "closed" }, { "group": "blue", "state": "running" }, { "group": "blue", "state": "running" }],
    grouped = function (array) {
        var r = [];
        array.forEach(function (a) {
            if (!this[a.group]) {
                this[a.group] = { group: a.group, running: 0, closed: 0, summary: 0 };
                r.push(this[a.group]);
            }
            this[a.group][a.state]++;
            this[a.group].summary++;
        }, Object.create(null));
        return r;
    }(data);

document.write('<pre>' + JSON.stringify(grouped, 0, 4) + '</pre>');