按年份和月份分组事件

dfty9e19  于 2021-09-13  发布在  Java
关注(0)|答案(2)|浏览(427)

我想将事件按年度和月份分组。我的数据如下所示:

const events = [
  {
    name: "event 1",
    year: 2021,
    month: 1,
  },
  {
    name: "event 2",
    year: 2021,
    month: 9,
  },
  {
    name: "event 3",
    year: 2021,
    month: 1,
  },
  {
    name: "event 4",
    year: 2022,
    month: 7,
  },
]

我的预期结果应该是这样的:

[
  {
    year: 2021,
    month: 1,
    events: [
      {
        name: "event 1"
      },
      {
        name: "event 3"
      }
    ]
  },
  {
    year: 2021,
    month: 9,
    events: [
      {
        name: "event 2"
      }
    ]
  }
]

这样做的最佳方法是什么?我发现了几个stackoverflow帖子,可以根据数组的键值对数组进行分组,但这不是我要找的。

const groupBy = (array, key) => {
  return array.reduce((result, currentValue) => {
    // If an array already present for key, push it to the array. Else create an array and push the object
    (result[currentValue[key]] = result[currentValue[key]] || []).push(currentValue);
    // Return the current iteration `result` value, this will be taken as next iteration `result` value and accumulate
    return result;
  }, {}); // empty object is the initial value for result object
};

const groupedByYear = groupBy(events, 'year');
6mzjoqzu

6mzjoqzu1#

你可以用它来做这个 reduceObject.values ```
const events = [
{
name: "event 1",
year: 2021,
month: 1,
},
{
name: "event 2",
year: 2021,
month: 9,
},
{
name: "event 3",
year: 2021,
month: 1,
},
];

const result = Object.values(events.reduce( (acc,evt) => {
const key = ${evt.year}-${evt.month};
if(!acc[key]) {
acc[key] = {year: evt.year, month: evt.month, events:[]}
}
acc[key].events.push( {name:evt.name} );
return acc;
},{}));

console.log(result);

sbdsn5lh

sbdsn5lh2#

您可以采用一种动态方法,为分组所需的属性使用一个组合键。
然后移除所有灌浆键,并推动一个没有不需要属性的新对象。

const
    events = [{ name: "event 1", year: 2021, month: 1 }, { name: "event 2", year: 2021, month: 9 }, { name: "event 3",  year: 2021, month: 1 }],
    keys = ['year', 'month'],
    result = Object.values(events.reduce((r, o) => {
        let value,
            key = keys.map(k => o[k]).join('|');

        if (!r[key]) r[key] = { ...Object.fromEntries(keys.map(k => [k, o[k]])), events: [] };

        r[key].events.push(keys.reduce((t, k) => (({ [k]: value, ...t } = t), t), o));
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

相关问题