简体   繁体   中英

Filter and group by key value

Below is my sample data,

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

Now I need to group all array items by its "Portfolio Lead" and push them to new array.

Below is my code,

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

Above code works, it's groups by its key, but I wanted the new array to be in this structure.

My current structure is like this,

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

But need it be like this

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

Currently I'm stuck with this please help.

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

const groupBy = (array, key) => {
  return Object.entries(array.reduce((result, currentValue) => ({
     ...result,
     [currentValue[key]]: [...(result[currentValue[key]] || []), currentValue]
  }), {})).map(ob => ({"Portfolio Lead": ob[0], oriData: ob[1], Count: ob[1].length}));
};

We can call Object.entries on the resulting value then call map on it to format it the way we want:

const groupBy = (array, key) => {
  return Object.entries(array.reduce((result, currentValue) => {
    (result[currentValue[key]] = result[currentValue[key]] || []).push(
      currentValue
    );
    return result;
  }, {})).map(v => ({[key]: v[0], count: v[1].length, oriData: v[1]}));
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM