[英]Group object by key with jsonata
I want to group and sum my following input data.我想对以下输入数据进行分组和汇总。
{"users": [
{
"ADMIN": [
{
"ADMIN_03": 46,
"ADMIN_01": 2
}
],
"CUSTOMER": [
{
"CUSTOMER_01": 1
}
]
},
{
"ADMIN": [
{
"ADMIN_03": 35
}
]
},
{
"ADMIN": [
{
"ADMIN_01": 12
}
],
"CUSTOMER": [
{
"CUSTOMER_03": 2
}
]
}
]}
The output should be grouped by the keys like "ADMIN" and the inner key/value pairs should be grouped and summed up. output 应按“ADMIN”等键分组,内部键/值对应分组汇总。
{ "users": [
{
"ADMIN":[
{
"ADMIN_01": 14
"ADMIN_03": 81,
},
"CUSTOMER":[
{
"CUSTOMER_01": 1,
"CUSTOMER_03": 2
}
]
}
Any ideas how to do this with JSONATA?任何想法如何用 JSONATA 做到这一点?
You can make use of reduce
and nested foreach
by taking Object.entries
:您可以通过使用Object.entries
来使用reduce
和嵌套的foreach
:
const users= [ { "ADMIN": [ { "ADMIN_03": 46, "ADMIN_01": 2 } ], "CUSTOMER": [ { "CUSTOMER_01": 1 } ] }, { "ADMIN": [ { "ADMIN_03": 35 } ] }, { "ADMIN": [ { "ADMIN_01": 12 } ], "CUSTOMER": [ { "CUSTOMER_03": 2 } ] }]; const result = users.reduce((a,o)=>{ Object.entries(o).forEach(([key, value])=>{ value.forEach(v=>{ Object.entries(v).forEach(([name, count])=>{ (a[key]??={})[name]??= 0; a[key][name]+=count; }); }); }); return a; },{}); console.log(result);
It seems that you need this result at the end.看来你最后需要这个结果。
data = {
users: [
{
ADMIN: [
{
ADMIN_03: 46,
ADMIN_01: 2,
},
],
CUSTOMER: [
{
CUSTOMER_01: 1,
},
],
},
{
ADMIN: [
{
ADMIN_03: 35,
},
],
},
{
ADMIN: [
{
ADMIN_01: 12,
},
],
CUSTOMER: [
{
CUSTOMER_03: 2,
},
],
},
],
};
function summerize(users) {
let result = { users: {} };
for (let i = 0; i < users.length; i++) {
const user = users[i];
for (const [username, userValue] of Object.entries(user)) {
if (typeof result.users[username] === "undefined")
result.users[username] = {};
for (let j = 0; j < userValue.length; j++) {
const item = userValue[j];
for (const [key, value] of Object.entries(item)) {
if (typeof result.users[username][key] === "undefined") {
result.users[username][key] = 0;
}
result.users[username][key] += value;
}
}
}
}
return result;
}
The result is结果是
{
"users": {
"ADMIN": { "ADMIN_03": 81, "ADMIN_01": 14 },
"CUSTOMER": { "CUSTOMER_01": 1, "CUSTOMER_03": 2 }
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.