在JSON中对唯一ID的数据进行透视

rwqw0loc  于 2023-08-08  发布在  其他
关注(0)|答案(1)|浏览(102)

我目前正在尝试透视(也许有一个更好的术语)表中的数据,以减少具有相似属性的记录。这是在一个typescript环境中完成的,我 * 应该 * 能够导入任何最有帮助的库。
JSON中的记录显示如下:

[
 {
  "record": "1",
  "host": "a",
  "task": "AMQPCSEA",
  "taskCount": "1",
  "processCount": 1
 }, {
  "record": "2",
  "host": "a",
  "task": "MANAGER",
  "taskCount": "1",
  "processCount": 1
 },{
  "record": "3",
  "host": "a",
  "task": "AMQFQPUB",
  "taskCount": "1",
  "processCount": 1
 },{
  "record": "4",
  "host": "b",
  "task": "AMQPCSEA",
  "taskCount": "1",
  "processCount": 2
 },{
  "record": "5",
  "host": "a",
  "task": "MANAGER",
  "taskCount": "1",
  "processCount": 1
 }
]

字符串
我想把数据表示成如下形式:

[
 {
  "host": "a",
  "MANAGER": {"processCount": 2}
  "AMQPCSEA": {"processCount": 1},
  "AMQFQPUB": {"processCount": 1},
 },{
  "host": "b",
  "AMQPCSEA": {"processCount": 2}
 }
]


我一直在尝试使用开源库中的一些聚合器函数和归约函数,但我对这项工作中所需的操作顺序感到有点不知所措。我希望有人能帮助我理解,为了在一个可能欠序的记录列表中获得每个“任务”每个“主机”的“进程”的聚合计数,我可以或应该采取什么类型的方法。我感谢任何帮助,我会尽力提供任何需要的信息。
谢谢你,谢谢

r1wp621o

r1wp621o1#

您可以使用Array.reduce迭代数据并将其分组。下面是一个带有一些注解的示例:

const data = [
  {
    record: "1",
    host: "a",
    task: "AMQPCSEA",
    taskCount: "1",
    processCount: 1,
  },
  {
    record: "2",
    host: "a",
    task: "MANAGER",
    taskCount: "1",
    processCount: 1,
  },
  {
    record: "3",
    host: "a",
    task: "AMQFQPUB",
    taskCount: "1",
    processCount: 1,
  },
  {
    record: "4",
    host: "b",
    task: "AMQPCSEA",
    taskCount: "1",
    processCount: 2,
  },
  {
    record: "5",
    host: "a",
    task: "MANAGER",
    taskCount: "1",
    processCount: 1,
  },
];

const result = data.reduce((acc, { r, host, task, t, processCount }) => {
  // Check if host already exists in acc
  const itemExists = acc.find((i) => i.host === host);

  if (itemExists) {
    // If hosts is found in acc, next check if the task exists as a key in acc
    const taskExists = acc.some((i) => i[task]);
    
    //Sum the process count if task already exists or record the process count as is
    itemExists[task] = taskExists
      ? { processCount: processCount + itemExists[task].processCount } 
      : { processCount };
  } else {
    //If host doesn't exist in acc, push new object with host into acc along with task and processCount
    acc.push({
      host,
      [task]: { processCount },
    });
  }

  return acc;
}, []);

console.log(result);

字符串

相关问题