按键值过滤和分组

问题描述 投票:0回答:2

下面是我的示例数据,

var data = [
  {
    "Employee Name": "Mr. X",
    "Portfolio Lead": "A"
  },
  {
    "Employee Name": "Mr. Y",
    "Portfolio Lead": "B"
  },
  {
    "Employee Name": "Mr. Z",
    "Portfolio Lead": "C"
  },
  {
    "Employee Name": "Mr. Q",
    "Portfolio Lead": "A"
  },
  {
    "Employee Name": "Mr. P",
    "Portfolio Lead": "A"
  }
];

现在我需要按"Portfolio Lead"将所有数组项分组,并将它们推到新数组。

下面是我的代码,

const groupBy = (array, key) => {
  return array.reduce((result, currentValue) => {
    (result[currentValue[key]] = result[currentValue[key]] || []).push(
      currentValue
    );
    return result;
  }, {});
};

以上代码有效,它是按其键分组的,但是我希望新数组位于此结构中。

我当前的结构是这样,

{
  "A": [
    {
      "Employee Name": "Mr. X",
      "Portfolio Lead": "A"
    },
    ...
  ],
  "B": [
    {
      "Employee Name": "Mr. Y",
      "Portfolio Lead": "B"
    }
  ],
  "C": [
    {
      "Employee Name": "Mr. Z",
      "Portfolio Lead": "C"
    }
  ]
}

但需要像这样

{
  "Portfolio Lead": "A",
  Count: 3,
  oriData: [....]
}

目前,我对此感到困惑,请提供帮助。

我的stackBlitz https://stackblitz.com/edit/typescript-nypqge?file=index.ts

javascript arrays typescript object multidimensional-array
2个回答
0
投票
我们可以在结果值上调用Object.entries,然后在其上调用Object.entries以所需的方式对其进行格式化:

map


0
投票
map
© www.soinside.com 2019 - 2024. All rights reserved.