按日期分组对象数组

Ala*_*hen 1 javascript momentjs lodash

我有一个看起来像这样的数据结构

const arr = [{
    name: "Alice",
    created_at : "2017-04-18"
},
{
    name: "James",
    created_at : "2017-06-30"
},
{
    name: "Melisa",
    created_at : "2017-04-03"
},
{
    name: "Amy",
    created_at : "2017-05-03"
}];
Run Code Online (Sandbox Code Playgroud)

我想重组它,以便我可以显示它们.我希望按月显示它们,就像这样

四月 - 爱丽丝 - 梅丽莎

梅 - 艾米

六月 - 詹姆斯

我不知道从哪里开始.

Gru*_*nny 11

这是一个使用时刻和lodash的解决方案.

首先,我们创建一个辅助函数,使用moment创建日期,然后提取缩短的月份名称.

// helper function to get the month name from an item
const monthName = item => moment(item.created_at, 'YYYY-MM-DD').format('MMM');
Run Code Online (Sandbox Code Playgroud)

现在使用lodash 日期分组,然后映射每个组以获取每个组的名称.以下代码段使用隐式链接:

// group items by month name and then get the name for each month
const result = _(arr)
    .groupBy(monthName)
    .mapValues(items => _.map(items, 'name'))
    .value()
Run Code Online (Sandbox Code Playgroud)

如上所述,但有明确的链接:

// group items by month name and then get the name for each month
const result = _.chain(arr)
    .groupBy(monthName)
    .mapValues(items => _.map(items, 'name'))
    .value()
Run Code Online (Sandbox Code Playgroud)

UPDATE

为了获得每个月的所有项目,它简化为:

const result = _.groupBy(arr, monthName);
Run Code Online (Sandbox Code Playgroud)

result 现在看起来像这样:

{
    Apr: [
        { name: "Alice", created_at : "2017-04-18" },
        { name: "Melisa", created_at : "2017-04-03" }
    ],
    Jun: .....
}
Run Code Online (Sandbox Code Playgroud)

  • 要按年和月分组,请将格式字符串更改为“YYYY-MMM”。结果对象中的键看起来像:'2017-Apr'等。恐怕我不知道反应所以可能值得发布第二个问题 (2认同)