Counting the number of alerts by type and partition from a JSON object
Compact Code

If you're looking for more compact code, you can start by avoiding redundant function declarations:


var dataKeys = data.map(function(element) {
  return Object.keys(element);
});



var dataKeys = data.map(Object.keys);


And a compact notation for an empty object.


var result = new Object();



var result = {};


Pivot Table

What you're doing is pivotting data from rows to columns. You are correct to mention reduce as this method could help us out here. It's possible to leave out the switch case if we just loop through the entries and aggregate the results.

var pivotTable = data.reduce((result, item) =&gt; {
  Object.entries(item).forEach(([key, val]) =&gt; {
    if (result[key] === undefined) {
      result[key] = { unknown: 0, ok: 0, warning: 0, ko: 0 };
    }
    result[key][val.alert]++;
  });
  return result;
}, {});

console.log(pivotTable);