使用两个键对 Json 数据进行分组并获得总计数

Group Json data with two keys and get the total count

有没有办法用 2 个键对 JSON 数组进行分组,并获取 Javascript 中分组对象键的计数。

需要 Javascript 中的解决方案。

https://pastebin.com/raw/FLB7vFhC

预期结果: counts 对象的长度应该仅为 5,所有键的总和组合在一起。

[
  {
    "totalCount": 3,
    "counts": [0,0,3,0,0],
    "productID": "tea1",
    "keyVal": "key5",
    "trend": "0"
  },
    {
    "totalCount": 4,
    "counts": [2,2,0,0,0],
    "productID": "tea1",
    "keyVal": "key1",
    "trend": "0"
  },
  {
    "totalCount": 11,
    "counts": [0,5,6,0,0],
    "productID": "group1",
    "keyVal": "key2",
    "trend": "0"
  },
  {
    "totalCount": 616,
    "counts": [101,507,8,0,0],
    "productID": "group1",
    "keyVal": "key1",
    "trend": "0"
 },
]

编辑:我错过了第二个钥匙

好了:

temp1 = pasteBin

中的 json 输入

你应该调整趋势变量,因为它没有指定如何计算它。

function groupBy(array, f) {
    var groups = {};
    array.forEach(function(o) {
        var group = JSON.stringify(f(o));
        groups[group] = groups[group] || [];
        groups[group].push(o);
    });
    return Object.keys(groups).map(function(group) {
        return groups[group];
    })
}

var result = groupBy(temp1, function(item) {
    return [item.keyVal, item.productID];
});

var output = [];
result.forEach(grouped => {
    var count = [0, 0, 0, 0, 0];
    var totalCount = 0;
    var trend = 0;
    var productID = grouped[0].productID;
    var keyVal = grouped[0].keyVal;
    grouped.forEach(value => {
        totalCount += value.totalCount;
        value.counts.forEach((x, i) => count[i] += x)
    })
    console.log(count);
    output.push({
        counts: count,
        keyVal: keyVal,
        totalCount: totalCount,
        productID: productID,
        trend: trend
    });
})