Reputation:
I am trying to group my datas by date: dates with the same year belong to a group. i want to group invoices by data_emissione,which have the following structure:
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"}
]
, but the following method returns nothing.
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();
});
},
Any kind of help would be appreciated
Upvotes: 0
Views: 1714
Reputation: 195
An attempt to make previous answer better:
// 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);
});
Just use object with keys - years and avoid using another data array.
Upvotes: 0
Reputation: 2096
This is what I do most of the times:
You can also use lodash groupBy
but most of the times I want an array or arrays and not an object of arrays.
// 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>
Upvotes: 2
Reputation: 4657
Remove .format()
and it should work:
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();
});
},
}
}
Upvotes: 0