我有一个对象有效负载的 JSON 数组,我需要根据多个键进行分组,并为分组中的每个对象添加两个新的键值对。第一个键值对是根据该组中的键值对求和,第二个键值对是从该组中获取最大值。我能够实现直到获得 groupby 但无法向该组中的每个对象添加新的键值对。这是输入和预期输出
输入:
[
{
"Key1": "Digital Media",
"Key2": "AAA",
"Key3": "2707878341.0",
"Key4": "116",
"Key5": "500",
"Key6": "66",
"Key7": "Delivery"
},
{
"Key1": "Digital Media",
"Key2": "AAA",
"Key3": "2707878341.0",
"Key4": "116",
"Key5": "50000",
"Key6": "11",
"Key7": "Delivery"
},
{
"Key1": "Media",
"Key2": "ABC",
"Key3": "2446140407.0",
"Key4": "116",
"Key5": "1400",
"Key6": "38",
"Key7": "Delivery"
}
]
预期输出:
[
{
"Key1": "Digital Media",
"Key2": "AAA",
"Key3": "2707878341.0",
"Key4": "116",
"Key5": "500",
"Key6": "66",
"Key7": "Delivery",
"Sum_Key6": 77,
"Max_Key5": "50000"
},
{
"Key1": "Digital Media",
"Key2": "AAA",
"Key3": "2707878341.0",
"Key4": "116",
"Key5": "50000",
"Key6": "11",
"Key7": "Delivery",
"Sum_Key6": 77,
"Max_Key5": "50000"
},
{
"Key1": "Media",
"Key2": "ABC",
"Key3": "2446140407.0",
"Key4": "116",
"Key5": "1400",
"Key6": "38",
"Key7": "Delivery",
"Sum_Key6": 38,
"Max_Key5": "1400"
}
]
下面是我尝试过的脚本,但我只得到 2 个对象,但我需要所有 3 个对象。
%dw 2.0
output application/json
---
((payload groupBy ($.Key2 ++ '_' ++ $.Key7 ++ '_' ++$.Key3)) pluck $) map {
"Key1" : $[0].Key1,
"Key2" : ($[0].Key2),
"Key3" : ($[0].Key3),
"Key4" : ($[0].Key4),
"Key5" : $[0].Key5,
"Key6" : $[0].Key6,
"Key7" : $[0].Key7,
"Sum_Key6": sum($.Key6),
"Max_Key5": max($.Key5)
}
有人可以帮助我吗? TIA
这个脚本会产生您正在寻找的内容
%dw 2.0
output application/json
var grouped = (payload groupBy ($.MasterCustCode ++ '_' ++ $.UsageType ++ '_' ++$.AcctIDDest))
---
flatten(
( grouped pluck $) map (groupArray, i) ->
do {
var groupSum = sum(groupArray.usagefile_UnitValue)
var groupMax = max(groupArray.To_Unit)
---
groupArray map (item, i2) -> item ++ {
"Sum_UnitValue": groupSum,
"Max_To_Unit": groupMax
}
}
)
groupBy
策略很好。
我添加了第二个
map
,这样您就可以在生成的组中逐个元素进行操作。
由于您生成的元素具有与原始元素相同的数据以及一些字段,因此我没有进行完整的映射。我刚刚添加了额外的字段。
最后,由于我有一个数组数组,我必须使用
flatten
来获取最终的单级数组。