javascript 对已按id分组的对象数组进行分组

gev0vcfq  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(141)

我有下面的JSON响应,它是作为远程对象下的ID组返回的。
然而,要在UI上显示,我需要根据名称分组后显示数据。有人可以建议我如何根据已经由后端API分组的数据的名称对数据进行分组吗?
有人能帮忙吗。
电流响应:

{
    "remote": {
      "12345": [
        {
          "id": "642232324873ab98",
          "name": "Akon",
          "account_id": "12345",
          "account_name": "director"
        }
      ],
      "56780": [
        {
          "id": "6434343a1873ab98",
          "name": "Jim",
          "account_id": "56780",
          "account_name": "director"
          
        }
      ],
      "others": [
        {
          "id": "6421ca1873ab980001bd465a",
          "account_id": null
          "account_name": "others"

        }
      ]
    }

远程对象的预期输出:

"remote": {
      "director": [
        {
          "id": "6420691873ab98",
          "name": "Akon",
          "account_id": "12345",
          "account_name": "director"
        },
        {
          "id": "622121873ab98",
          "name": "Jim",
          "account_id": "56780",
          "account_name": "director"
          
        }
      ],
      "others": [
        {
          "id": "6421ca1873ab980001bd465a",
          "account_id": null,
          "account_name": "others"

        }
      ]
    }
    ```
dwbf0jvd

dwbf0jvd1#

这是一个非常简单的聚合,代码希望是相当自我解释的。它获取remote下的所有条目,并尝试将它们聚合到一个新数组中,该数组由account_name或字符串“other”(如果不存在)分组。

const input = {"id":"43940djkd334","topic":"local topic","start_time":"2023-03-27T16:01:16.000+00:00","duration":2223,"state":"fetched","user":{"local":[{"id":"6421ca1873ab980001bd4658","name":"Freddy","email":"freddy@testmail.io","title":null,"account_id":"62323jkds0203nsk","account_name":"testmail.io"}],"remote":{"12345":[{"id":"642232324873ab98","name":"Akon","account_id":"12345","account_name":"director"}],"56780":[{"id":"6434343a1873ab98","name":"Jim","account_id":"56780","account_name":"director"}],"others":[{"id":"6421ca1873ab980001bd465a","account_id":null}]}}};

const output = Object.entries(input.user.remote).reduce( (acc,[_,[item]]) => {
  acc[item.account_name ?? "others"] ??= [];
  acc[item.account_name ?? "others"].push(item);
  return acc;
},{})

console.log(output);

相关问题