JSONata(或 JS)- 分组和求和 JSON 数组/对象

JSONata (or JS) - group and sum JSON array / objects

我想 'groupsum' 来自以下数组的带有 JSONata 的对象数组:

payload = [
 {"id":"Irr-1","name":"Irrigation","timedif_s":7.743},
 {"id":"Irr-2","name":"Irrigation","timedif_s":2.749},
 {"id":"Lig-2","name":"Lights","timedif_s":1.475},
 {"id":"Irr-1","name":"Irrigation""timedif_s":1.07},]

结果必须如下所示:

[{"name":"Irrigation", "sumtimedif": 11.562},
 {"name":"Lig-1", "sumtimedif": 1.475}]

我试过:

payload.name{"name":payload.name,"sumtimedif":$sum(timedif_s)}

但我只返回一个空字符串。

{ empty }

有什么建议吗?

我发现了另一个对我有帮助的post:Most efficient method to groupby on a array of objects

不确定这是否可以在JSONata中完成,所以我恢复到JS,如下:

var arr = msg.payload ;
arr1 = groupBy(arr, 'name', 'timedif_s' ) ;
msg.payload = arr1 ;
return msg;
//---------------------------------------------
function groupBy(array, col, value) {
    var r = [], o = {};
    array.forEach(function (a) {
        if (!o[a[col]]) {
            o[a[col]] = {};
            o[a[col]][col] = a[col];
            o[a[col]][value] = 0;
            r.push(o[a[col]]);
        }
        o[a[col]][value] += +a[value];
    });
    return r;
}

以下 JSONata 表达式将执行此操作:

payload{
  name: $sum(timedif_s)  /* group by name */
} ~> $each(function($v, $k) {
 {"name": $k, "sumtimedif": $v}  /* transform each key/value pair */
})

表达式的第一部分进行分组和聚合,第二部分将每个组(key/value 对)转换为您想要的格式。 http://try.jsonata.org/ByxzyQ0x4