按日期(年份)Vue.js分组数据

时间:2018-10-22 08:55:56

标签: javascript vue.js group-by

我正在尝试按日期对数据进行分组:同一年份的日期属于一个组。 我想按data_emissione将发票分组,其结构如下:

        invoices: [
         {id,data_emissione:"2017-06-19 00:00:00"},
         {id,data_emissione:"2017-05-19 00:00:00"},
         {id,data_emissione:"2018-06-24 00:00:00"}
        ]

,但是以下方法不返回任何内容。

export default {
        data(){
            return {
                invoices:[],
                groups:{}

            }
        },
 mounted(){
            this.getMine();
            this.groupInvoices();
        },
 methods:{
            groupInvoices(){
                var self = this;
                var groups = _.groupBy(self.invoices,function(d){
                    return moment(d.data_emissione).year().format();
                });

            },

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:0)

删除.format(),它应该可以正常工作:

export default {
    data(){
        return {
            invoices:[
                {data_emissione:"2017-06-19 00:00:00"},
                {data_emissione:"2017-05-19 00:00:00"},
                {data_emissione:"2018-06-24 00:00:00"}
            ],
            groups: {}
        }
    },
    mounted(){
        this.getMine();
        this.groupInvoices();
    },
    methods:{
        groupInvoices(){
            var self = this;
            var this.groups = _.groupBy(self.invoices,function(d){
                return moment(d.data_emissione).year();
            });

        },
    }
}

答案 1 :(得分:0)

这是我大部分时间所做的:

  1. 检索原始数据
  2. 格式化道具并添加道具
  3. 处理格式化数据

您也可以使用lodash groupBy,但是大多数时候我想要一个或多个数组而不是数组的对象。

// retrieve
let invoices = [
  {id: 1, data_emissione: "2017-06-19 00:00:00"},
  {id: 2, data_emissione: "2017-05-19 00:00:00"},
  {id: 3, data_emissione: "2018-06-24 00:00:00"}]
  
// format  
let formattedInvoices = invoices.map(elem => ({
  id: elem.id,
  data_emissione: elem.data_emissione,
  year: moment(elem.data_emissione).year()
}));

// manipulate
let groupedInvoices = [2017, 2018].map(year => formattedInvoices.filter(elem => elem.year === year))

console.log(groupedInvoices)
<script src="https://momentjs.com/downloads/moment.min.js"></script>

答案 2 :(得分:0)

尝试使先前的答案更好:

// retrieve
const invoices = [
    {id: 1, data_emissione: "2017-06-19 00:00:00"},
    {id: 2, data_emissione: "2017-05-19 00:00:00"},
    {id: 3, data_emissione: "2018-06-24 00:00:00"}]

  const groupedInvoices = {};

  invoices.forEach((invoice) => {
    const year = moment(invoice.data_emissione).year();
    groupedInvoices[year] = groupedInvoices[year] || [];
    groupedInvoices[year].push(invoice);
  });

只需使用带有键的对象-年,并避免使用其他数据数组。