问题
I have JSON array object which contains dates. I want to get displayed unique Month and Year(ignore day)from date. Please find my JSON object as below:
{
"records"[
{
"id":"833599",
"date":1507624517000,
},
{
"id":"828140",
"date":1506346215000,
},
{
"id":"817349",
"date":1504852602000,
},
{
"id":"817347",
"date":1504851799000,
},
{
"id":"817346",
"date":1504851689000,
},
{
"id":"811693",
"date":1504086405000,
},
{
"id":"721986",
"date":1501140629000,
},
{
"id":"673227",
"date":1499435543000,
},
{
"id":"673196",
"date":1499433640000,
},
{
"id":"673190",
"date":1499433410000,
},
{
"id":"673188",
"date":1499433170000,
},
{
"id":"673171",
"date":1499432516000,
},
{
"id":"672075",
"date":1499336767000,
},
{
"id":"642516",
"date":1498122509000,
},
{
"id":"632547",
"date":1497350369000,
},
{
"id":"632546",
"date":1497350336000,
},
{
"id":"632545",
"date":1497350257000,
},
{
"id":"632543",
"date":1497350221000,
},
{
"id":"631750",
"date":1497256103000,
},
{
"id":"624957",
"date":1496820632000,
},
{
"id":"621103",
"date":1496237026000,
},
{
"id":"620648",
"date":1496220870000,
},
{
"id":"613655",
"date":1495813509000,
},
{
"id":"610014",
"date":1495617958000,
},
{
"id":"609984",
"date":1495601967000,
},
{
"id":"603345",
"date":1495188742000,
},
{
"id":"596499",
"date":1494932889000,
},
{
"id":"596459",
"date":1494914330000,
},
{
"id":"587822",
"date":1494510858000,
}
]
}
I want get output as below:
October 2017
September 2017
August 2017
July 2017
June 2017
May 2017
I tried to use
<div *ngFor="let record of records" class="month-row">
<div class="month-name">{{ record.date | date: 'MMMM yyyy'}}</div>
</div>
But getting below result:
October 2017
September 2017
September 2017
September 2017
September 2017
August 2017
August 2017
July 2017
July 2017
July 2017
June 2017
May 2017
May 2017
May 2017
May 2017
Could you please help to get unique Month and year from this date so month and year shouldn't be duplicate?
Also, Please note if year is different then month can be repeat.
回答1:
You need to create one pipe
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'filterMonthYear' })
export class UniqueMonthYearPipe implements PipeTransform {
transform(dates) {
var updated_dates = dates.map(date => {
var d = new Date(date.date);
return (d.getMonth()+1) + '/' + d.getFullYear();
});
return Array.from(new Set(updated_dates));
}
}
And use it like :
<div *ngFor="let record of (records.records | filterMonthYear)">
{{record}}
</div>
Here is the link to working example :
https://stackblitz.com/edit/angular-filter-pipe
来源:https://stackoverflow.com/questions/47048785/how-to-make-ngfor-filter-out-duplicate-month-and-year-from-date-in-angular-2