0

我想对以下输入数据进行分组和汇总。

{"users": [
  {
    "ADMIN": [
      {
        "ADMIN_03": 46,
        "ADMIN_01": 2
      }
    ],
    "CUSTOMER": [
      {
        "CUSTOMER_01": 1
      }
    ]
  },
  {
    "ADMIN": [
      {
        "ADMIN_03": 35
      }
    ]
  },
  {
    "ADMIN": [
      {
        "ADMIN_01": 12
      }
    ],
    "CUSTOMER": [
      {
        "CUSTOMER_03": 2
      }
    ]
  }
]}

输出应按“ADMIN”之类的键分组,内部键/值对应分组和汇总。

{    "users": [
      {
        "ADMIN":[
          {
             "ADMIN_01": 14
             "ADMIN_03": 81,
          },
        "CUSTOMER":[
          {
             "CUSTOMER_01": 1,
             "CUSTOMER_03": 2
          }
    ]
}

任何想法如何用 JSONATA 做到这一点?

4

2 回答 2

2

您可以通过以下方式使用和reduce嵌套:foreachObject.entries

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);

于 2021-03-09T14:41:42.660 回答
0

看来你最后需要这个结果。

    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;
}

结果是

{
  "users": {
    "ADMIN": { "ADMIN_03": 81, "ADMIN_01": 14 },
    "CUSTOMER": { "CUSTOMER_01": 1, "CUSTOMER_03": 2 }
  }
}
于 2021-03-09T15:23:54.523 回答