简体   繁体   English

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

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

I want to 'groupsum' an array of objects with JSONata, from the following array: 我想使用以下数组从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},]

The results must look like: 结果必须如下所示:

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

I have tried: 我努力了:

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

But I only get back an empty string. 但是我只得到一个空字符串。

{ empty }

Any advise? 有什么建议吗?

The following JSONata expression will do this: 以下JSONata表达式将执行此操作:

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

The first part of the expression does the grouping and aggregation, and the second part transforms each group (key/value pair) into the format you want. 表达式的第一部分进行分组和聚合,第二部分将每个组(键/值对)转换为所需的格式。 http://try.jsonata.org/ByxzyQ0x4 http://try.jsonata.org/ByxzyQ0x4

I found another good post that helped me: Most efficient method to groupby on a array of objects . 我找到了另一篇对我有帮助的好文章: 对一组对象进行分组的最有效方法

Not sure if this can be done in JSONata, so I reverted to JS, as follows: 不知道是否可以在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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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