我有包含日期的JSON数组对象。我希望从日期开始显示唯一的月份和年份(忽略日期)。请找到我的JSON对象,如下所示:
{
"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,
}
]
}
我想获得如下输出:
October 2017
September 2017
August 2017
July 2017
June 2017
May 2017
我尝试使用
<div *ngFor="let record of records" class="month-row">
<div class="month-name">{{ record.date | date: 'MMMM yyyy'}}</div>
</div>
但低于结果:
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
您能否帮助从这个日期获得独特的月份和年份,因此月份和年份不应该重复?
此外,请注意,如果年份不同,则可以重复月份。
答案 0 :(得分:3)
您需要创建一个管道
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));
}
}
并使用它:
<div *ngFor="let record of (records.records | filterMonthYear)">
{{record}}
</div>
以下是工作示例的链接: