javascript - 如何使用 Lodash / Underscore 进行以下数据处理分组处理
大家讲道理
大家讲道理 2017-04-11 10:28:20
0
1
664

有以下格式的 json:

[
    {
        id: 1,
        created: "2016-05-04 15:12:40",
        content: '...'
    },
    {
        id: 2,
        created: "2016-02-04 15:12:40",
        content: '...'
    },
    {
        id: 3,
        created: "2015-12-04 15:12:40",
        content: '...'
    },
]

使用 Lodash 的 groupBy 函数 return created 的月份将会得到以下结果。。

{
    5: [{
        id: 1,
        created: "2016-05-04 15:12:40",
        content: '...'
    }],
    2: [{
        id: 2,
        created: "2016-02-04 15:12:40",
        content: '...'
    }],
    5: [{
        id: 3,
        created: "2015-12-04 15:12:40",
        content: '...'
    }],
    
}

如何处理得到以下结果

[
    {
        month: '本月',
        data: [
            {
                id: 1,
                created: "2016-05-04 15:12:40",
                content: '...'
            }
        ]
    },
    {
        month: '4月',
        ...
    }
]

已自行解决

const groupedByMonth = groupBy(this.incomes, item =>
  item.updated_at.substring(0, 7)
);
const result = reduce(groupedByMonth, (res, data, date) => {
  res.push({ date, data });
  return res;
}, []);
return result;
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(1)
洪涛
var re=_.groupBy(arr,function(item){
    return (new Date(item.created).getMonth());
})
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!